Android開機和關機廣播監聽

Main-zy發表於2014-08-18
Android開機、關機廣播監聽
一、開機廣播的監聽
1.在AndroidManifest.xml檔案註冊接收開機廣播
<receiver android:name=".XXXBroadcastReceiver" >  
            <intent-filter>   
<!-- 開機廣播 -->     <action android:name="android.intent.action.BOOT_COMPLETED" />  
            </intent-filter>   
        </receiver>  

 
2.在BroadcastReceiver裡執行要做的事情
 
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檔案註冊接收關機廣播
<receiver android:name=".XXXBroadcastReceiver" >  
            <intent-filter>   
                <!-- 關機廣播 -->  
                <action android:name="android.intent.action.ACTION_SHUTDOWN" />  
            </intent-filter>   
        </receiver>   



2.在BroadcastReceiver裡執行要做的事情
public class XXXBroadcastReceiver extends BroadcastReceiver {  
    @Override  
    public void onReceive(Context context, Intent intent) {  
        //關機要處理的事情  
    }  
} 

 

相關文章