Android | 开机自启,监听BOOTCOMPLETE

思路

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

  1. 添加权限<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
  2. 创建广播接收器,收到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);
       }
   }
}
  1. 静态注册广播接收器
   		<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>
  1. 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对用户可见的时候,系统让屏幕处于高亮状态。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

指针不南

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值