android 开机自启动实现

时间:2023-03-08 16:36:11

  

  App的开机自启动可以通过注册广播接收器接收开机广播来实现,具体步骤如下:

1.创建 BroadcastReceiver 的派生类,并重写 onReceive() 函数:

 /**
* Created by Haoye on 2016/3/8.
* Copyright © 2016 Haoye All Rights Reserved
*/
public class BootReceiver extends BroadcastReceiver { @Override
public void onReceive(Context context, Intent intent) {
Intent startIntent = new Intent(context, MainActivity.class);
startIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startIntent.setAction(Intent.ACTION_MAIN);
startIntent.addCategory(Intent.CATEGORY_LAUNCHER); context.startActivity(startIntent);
}
}

2. 在AndroidManifest.xml 文件中注册广播接收器:

 <receiver android:name=".BootReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/> <category android:name="android.intent.category.HOME"/>
</intent-filter>
</receiver>

当然也能在java代码中用 registerReceiver() 函数注册和添加权限,并在需要取消时用 unregisterReceiver() 函数取消;

3.在AndroidManifest.xml 文件中添加自启动权限:

 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

4.测试:

安装运行-->关闭手机-->启动手机

注意自启动权限有没有被禁止...