前言
应用自启动主要是通过接收系统广播BOOT_COMPLETED
来实现的,在receiver中执行APP启动的方法。
实现
1. AndroidManifest.xml文件中添加BOOT监听权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
2. 在manifest根目录下设置为安装方式
<manifest xmlns:android="http://schemas.android.com/apk/res/android
...
android:installLocation="internalOnly">
设置为将应用安装到内部存储中,安装在SD卡中可能会导致自启动失败。
3. 广播注册
AndroidManifest.xml
<receiver
android:name=".BootBroadcast"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
4. receiver中添加应用启动逻辑
示例代码如下:下面代码里的包名记得修改
package com.example.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* 文 件 名: BootBroadcast
* 创 建 人: Ace.Wu
* 创建日期: 2017/8/25 20:02
* 修改时间:
* 修改备注:
*/
public class BootBroadcast extends BroadcastReceiver{
private static final String ACTION = "android.intent.action.BOOT_COMPLETED";
private static final String TAG = "StartBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent){
Log.d(TAG,"开机启动了");
if (intent.getAction().equals(ACTION)){
Log.d(TAG,"开机启动了接收到了");
// Intent i = new Intent(context,MainActivity.class);
Intent newIntent = context.getPackageManager()
.getLaunchIntentForPackage("com.example.myapplication");
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(newIntent);
Log.d(TAG,"开机启动了接收到了^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
}
}
}
设置一下应用启动逻辑。
问题说明
在执行如上步骤之后,在模拟器运行已经可以启动后应用重启。
但是在手机上测试可以会无法启动,原因是手机上可能安装有手机管家之类的软件。需要在其中将当前应用的自启动选项打开才能生效。
可能会很慢很慢多等一会
也可以修改android:priority
稍微提速