BroadcastReceiver 用於處理 BOOT COMPLETED 事件

下面的示例顯示瞭如何建立能夠接收 BOOT_COMPLETED 事件的 BroadcastReceiver。通過這種方式,你可以在裝置啟動後立即啟動 Service 或啟動 Activity

此外,你可以使用 BOOT_COMPLETED 事件來恢復警報,因為它們會在裝置斷電時被銷燬。

注意: 使用者需要至少啟動一次應用程式才能收到 BOOT_COMPLETED 操作。

AndroidManifest.xml 中

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.example" >
    ...
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    ...

    <application>
        ...

        <receiver android:name="com.test.example.MyCustomBroadcastReceiver">
        <intent-filter>
                <!-- REGISTER TO RECEIVE BOOT_COMPLETED EVENTS -->
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

MyCustomBroadcastReceiver.java

public class MyCustomBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if(action != null) {
            if (action.equals(Intent.ACTION_BOOT_COMPLETED) ) {
                // TO-DO: Code to handle BOOT COMPLETED EVENT
                // TO-DO: I can start an service.. display a notification... start an activity
            } 
        }
    }
}