android开机自动运行APP实现方式其实很简单。在android系统运行时,会发出“android.intent.action.BOOT_COMPLETED”这个系统广播,因此我们监听它,并进行打开APP的操作即可。现在大多数的android手机系统都默认禁止第三方安装的APP开机自启动,只有系统APP(system/app)才默认有这个权限,所以一般都需要去安全中心或者手机管家中去设置为允许。这里说个题外话,手机软件除非特殊情况,不然最好不要做开机自启动,开机自启动一般适用于android系统的终端机上,开机即运行相应的项目,该机器上也只有这个项目,下面上代码。

新建一个类AutoStartBroadcastReceiver集成自BroadcastReceiver:

public class AutoStartBroadcastReceiver extends BroadcastReceiver {    private static final String ACTION = "android.intent.action.BOOT_COMPLETED";    @Override    public void onReceive(Context context, Intent intent) {        //开机启动        if (ACTION.equals(intent.getAction())) {            Intent mainIntent = new Intent(context, MainActivity.class);//MainActivity.calss为你要打开的界面,如果没有界面就可以用service代替            // 在BroadcastReceiver中显示Activity,必须要设置FLAG_ACTIVITY_NEW_TASK标志            mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);            context.startActivity(mainIntent);        }    }}

在AndroidManifest.xml文件中设置权限和注册广播:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <receiver android:name=".AutoStartBroadcastReceiver" >            <intent-filter>                <action android:name="android.intent.action.BOOT_COMPLETED" />                <category android:name="android.intent.category.HOME" />            intent-filter> receiver>

如此,代码部分就完成,可以进行测试了!我在android7.0的模拟器和Android6.0的真机(魅族)上都测试过,实现的预期的功能。下面提供两个通过adb发送“BOOT_COMPLETED”系统广播的命令:

1.adb shell am broadcast -a android.intent.action.BOOT_COMPLETED
adb发送系统广播至android设备

2.adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -c android.intent.category.HOME -n component
adb发送系统广播至android设备指定的组件中,-n后面接的是你指定项目所需接收广播的类的全路径,而并非大多网上所说的packagename,比如我项目中即为:”com.android.qrcode/.AutoStartBroadcastReceiver”

以上两个命令也都是亲测有效的,如果还有不明白的地方,欢迎留言!

更多相关文章

  1. 开源项目之Android Afinal框架
  2. 初入Android~系统化学习必备(转自http://bbs.weand.com/read-htm-
  3. Android启动界面优化技巧-Splash Screens的正确方式
  4. Android实现界面刷新
  5. mac上AndroidStudio自带的SDK manager 系统菜单显示问题
  6. Android输入系统
  7. Android项目开发完成以后就要将android项目文件打包成apk文件
  8. 从Android项目学习Kotlin(一)
  9. Android系统的内存管理研究

随机推荐

  1. Android(安卓)HandlerThread 详解
  2. Android(安卓)Map开发基础知识学习笔记
  3. [Android(安卓)NDK] Android(安卓)NDK开
  4. (四)Android事件分发机制 - 总结篇
  5. Android(安卓)Studio 活动的启动模式 sta
  6. java.lang.IllegalStateException: Could
  7. android字体小结
  8. Android关机重启实现
  9. input系统一 loop线程的创建与运行
  10. android监听短信