首页 > 代码库 > 开机自启监听

开机自启监听

一、创建一个类使其继承BroadcastReceiver并且复写onReceive方法

public class BootReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        //开启main Activity
        Intent autoRestart = new Intent(context, MainActivity.class);
        //如果要在广播里开启Activity需要设置一个任务栈环境
        autoRestart.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(autoRestart);
    }
}

二、在AndroidManifest.xml中配置开机启动事件监听和权限

 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
...
<receiver android:name=".BootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
</receiver>

 

开机自启监听