思路
Intent | Android 开发者 | Android Developers
- Broadcast Action: This is broadcast once, after the user has finished booting. It can be used to perform application-specific initialization, such as installing alarms. You must hold the permission in order to receive this broadcast. Manifest.permission.RECEIVE_BOOT_COMPLETED
- This broadcast is sent at boot by all devices (both with and without direct boot support). Upon receipt of this broadcast, the user is unlocked and both device-protected and credential-protected storage can accessed safely.
- If you need to run while the user is still locked (before they’ve entered their lock pattern or PIN for the first time), you can listen for the broadcast. ACTION_LOCKED_BOOT_COMPLETED
选择监听BOOTCOMPLETED来实现开机自启
BOOT_COMPLETED在ActivityManagerService中由系统发送。
BOOT_COMPLETED会在系统启动完成发送一次,只发送一次
manifest中添加权限
静态注册广播接收器接受系统发送的BOOT_COMPLETED
步骤
manifest.xml
- 添加权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
- 创建广播接收器,收到BOOT_COMPLETED,启动Activity
public class MyReceiver extends BroadcastReceiver
{
public MyReceiver()
{
}
@Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction() != null && intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
- 静态注册广播接收器
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="2147483647">
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
- Activity 中点亮屏幕
以下代码添加在Activity的onCreate中
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | // 使用这个flag时,系统会自动解锁屏幕。
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | // 当window被显示的时候,系统把FLAG_TURN_SCREEN_ON当做一个用户活动事件,用以点亮屏幕。
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // 当window对用户可见的时候,系统让屏幕处于高亮状态。