利用BroadcastReceiver静态注册的原理,可以完成apk自启动, 要想apk能在设备启动完后自启动,只需要做到如下:
1.在java中加
public static class MyBootReceiver extends BroadcastReceiver {
@Override
public void onReceive (final Context context, Intent intent){
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
Log.d(TAG, "BOOT FINISHED");
Intent tmpIntent = new Intent();
tmpIntent.setClass(context, HeheServiceActivity.class);
tmpIntent.addFlags(intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(tmpIntent);
}
}
}
2. 在AndroidManifest.xml中加入:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name=".HeheServiceActivity$MyBootReceiver"
android:exported="true"
android:process=":remote"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.HOME"/>
</intent-filter>
</receiver>
代码上只要实现上面两步就可以自启动了。
失败的问题:
但我在实现过程中遇到问题,失败log如下:
D ActivityManager: prevent start ComponentInfo{heheservice.android.com.heheservice/heheservice.android.com.heheservice.HeheServiceActivity$MyBootReceiver}
BroadcastQueue: Unable to launch app heheservice.android.com.heheservice/10046 for broadcast Intent { act=android.intent.action.BOOT_COMPLETED flg=0x8000010 (has extras) }: process is bad
之所以出现这个错误,是因为源码中ActivityManagerService.java中startProcessLocked对启动的apk加了限制,这个限制是针对包名的,于是我修改了包名,对于Android Studio工程的话,还需要修改一下build.gradle文件中applicationId "com.android.com.heheservice",修改完后就能成功自启动了。