Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android 開機自啟動 Service 的實作

編輯:進階開發

本文示範如何透過 BroadcastReceiver 監聽開機廣播,進而在開機完成後自動啟動一個 Service,並由該 Service 定時執行工作。以下分為接收者、Service、被啟動的 Activity 與 Manifest 四個部分說明。

一、開機廣播接收者

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class yourReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, ServiceTest.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startService(i);
    }
}

二、Service 類別

這個 Service 透過 Handler 定時觸發工作,範例中於特定時段啟動一個 Activity:

package radar.com;

import java.util.Calendar;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class ServiceTest extends Service {
    Handler hd1 = new Handler();
    boolean b;   // 啟動 Activity 的開關
    int time;
    private static final String TAG = "TestService";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Log.e(TAG, "==========> TestService.onCreate");
        hd1.postDelayed(mTasks, delay);
    }

    public void log() {
        Calendar c = Calendar.getInstance();
        int h = c.getTime().getHours();
        int m = c.getTime().getMinutes();
        Log.i("hour", "" + h);
        Log.i("minute", "" + m);
        // 時機判斷,可依需求自行定義提醒時間
        if (h == 16 && m == 10) {
            if (!b) {
                Intent i = new Intent();
                i.setClass(ServiceTest.this, showActivity.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                this.startActivity(i);
                this.stopSelf();
                b = true;
            }
        }
        // 開關開啟後計時,避免短時間內重複啟動
        if (b) {
            time += 5;
            if (time == 60) {
                time = 0;
                b = false;
            }
        }
    }

    private int delay = 5000; // 速度控制參數(毫秒)

    private Runnable mTasks = new Runnable() {
        public void run() {
            log();
            hd1.postDelayed(mTasks, delay);
        }
    };
}

三、被啟動的 Activity

package radar.com;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class showActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
    }
}

四、AndroidManifest.xml 註冊

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="radar.com"
    android:versionCode="1"
    android:versionName="1.0">
    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name">
        <service
            android:name=".ServiceTest"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </service>
        <receiver android:name=".yourReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.HOME"/>
            </intent-filter>
        </receiver>
        <activity android:name=".showActivity"
            android:label="@string/app_name"
            android:configChanges="orientation|keyboardHidden|navigation"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="4" />
</manifest>

重點提醒

別忘了在 Manifest 中加入 RECEIVE_BOOT_COMPLETED 權限,並正確註冊 receiver 與 service。透過 Handler 的 postDelayed 即可實現週期性任務,而 boolean 開關則能避免任務在短時間內被重複觸發。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved