• Android 实现开机自启APP


    本文为作者原创,转载请注明出处,谢谢配合
    作者:stars-one
    链接:https://www.cnblogs.com/stars-one/p/16329968.html

    本篇大约有2165个字,阅读预计需要2.71分钟


    原文地址:Android 实现开机自启APP - Stars-One的杂货小窝

    公司有个项目,需要实现自启动的功能,本来想着是设置桌面启动器的方式去实现,但是设备是华为平板(EMUI系统),不允许设置第三方桌面

    且监听开机广播也无效,本来以为没法实现了,没想到公司的另一款APP确实支持,于是便是研究了下,发现监听开机广播的方式,还需要加上个悬浮窗权限即可实现功能

    然后也是趁着机会来总结下

    方法1(启动页)

    在AndroidMainfest中,将首页的Activity设置一下属性即可

    <activity
        android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <category android:name="android.intent.category.HOME" />
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    

    方法2(监听开机广播)

    使用静态广播实现自启功能

    1.广播及权限声明

    AndroidManifest文件中声明权限:

    <!--    开机监听-->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <!--    悬浮窗-->
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    

    声明广播:

    <receiver
        android:name=".AutoStartReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter android:priority="1000">
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    

    2.广播类实现

    AutoStartReceiver类代码实现:

    public class AutoStartReceiver extends BroadcastReceiver {
    
    
        @Override
        public void onReceive(Context context, Intent intent) {
            //开机启动
            if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
                Intent thisIntent = new Intent(context, MainActivity.class);//设置要启动的app
                thisIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(thisIntent);
            }
        }
    }
    

    3.悬浮窗权限申请

    在主Activity里申请悬浮窗权限

    //检查是否已经授予权限,大于6.0的系统适用,小于6.0系统默认打开,无需理会
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
        //没有权限,须要申请权限,由于是打开一个受权页面,因此拿不到返回状态的,因此建议是在onResume方法中重新执行一次校验
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }
    

    测试补充

    测试时候需要注意,使用这种方法,都是需要启动一次APP,之后自启才会实现

    手中有台Android11的设备,测试发现不加悬浮窗,也是无法在开机后启动APP

    而华为平板里的系统是Android10,所以断定Android 10以上估计都要申请悬浮窗权限才能实现

    同事的手机是鸿蒙系统,加了悬浮窗还是无法自启

    注意:
    华为手机或平板都需要去设置应用的启动管理,其他系统可参考此设置

  • 相关阅读:
    基于Laravel 5.6的运动健身类小程序前后端源码
    微信小程序-云开发 起步
    MySQL高级语句(三)——存储过程
    图像的特征点描述与提取
    【数据结构】带头双向链表的简单实现
    密码管理的艺术:数据库存储密码的策略、技术和工具
    Cmake输出git内容方式
    手写RPC框架--6.封装报文
    最大异或对
    【.NET源码解读】Configuration组件及自动更新
  • 原文地址:https://www.cnblogs.com/stars-one/p/16329968.html