首页 > 代码库 > Android开机和关机广播监听

Android开机和关机广播监听

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) {  
        //关机要处理的事情  
    }  
}