一、開機廣播的監聽
1.在AndroidManifest.xml文件注冊接收開機廣播
[java]
<receiver android:name=".XXXBroadcastReceiver" >
<intent-filter>
<!-- 開機廣播 --> <action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
2.在BroadcastReceiver裡執行要做的事情
[java]
public class XXXBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent newIntent = new Intent(context, XXX);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //注意,必須添加這個標記,否則啟動會失敗
context.startActivity(newIntent);
}
}
}
二、關機廣播的監聽
1.在AndroidManifest.xml文件注冊接收關機廣播
[java]
<receiver android:name=".XXXBroadcastReceiver" >
<intent-filter>
<!-- 關機廣播 -->
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
</intent-filter>
</receiver>
2.在BroadcastReceiver裡執行要做的事情
[java]
public class XXXBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//關機要處理的事情
}
}