方案一
将app做成系统应用,直接安装在 system/app 目录下
具体步骤为:
1.在AndroidManifest文件中,添加
android:sharedUserId="android.uid.system"
例如:
2.将您的apk直接通过adb命令push到system/app下面,重启手机即可
方案二
1.创建一个广播接收者
package itbird.com.myapplication33;import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import java.util.List;/*** Created by xfkang on 2018/5/7.*/public class MyReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {if (intent == null) {return;}Log.d("MyReceiver", intent.getAction());if (!isRun(context, "itbird.com.myapplication33")) {intent.setClass(context, MainActivity.class);intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);context.startActivity(intent);}}/*** 判断应用是否在运行** @param context* @return*/public boolean isRun(Context context, String packagename) {ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);boolean isAppRunning = false;//100表示取的最大的任务数,info.topActivity表示当前正在运行的Activity,info.baseActivity表系统后台有此进程在运行for (ActivityManager.RunningTaskInfo info : list) {if (info.topActivity.getPackageName().equals(packagename) || info.baseActivity.getPackageName().equals(packagename)) {isAppRunning = true;Log.d("ActivityService isRun()", info.topActivity.getPackageName() + " info.baseActivity.getPackageName()=" + info.baseActivity.getPackageName());break;}}Log.d("ActivityService isRun()", "com.ad 程序 ...isAppRunning......" + isAppRunning);return isAppRunning;}
}
2.给receiver配置对应intent-filter
<receiver android:name=".MyReceiver"><intent-filter><action android:name="ITBIRD.TEST.ACTION"/></intent-filter></receiver>
3.添加权限,缺少这步则无法在Android 3.0及其之前版本上自启动
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
注意
1.由于Android系统在外置SD卡加载前广播ACTION_BOOT_COMPLETED,于是如果应用安装在外置SD卡上,它无法接收到此广播
2.FLAG_INCLUDE_STOPPED_PACKAGES的问题,请阅读《Android应用在未启动的情况下接受指定广播》