在Android11上App不能开机自启的解决

2023年04月26日 1484点热度 0人点赞 0条评论

最近在做一个收票系统闸机自动控制,机器内置的控制板是Android11系统,需要在上面跑App来实际扫门票上的二维码自动开门。
前面一切顺利,但最后遇到了个莫名其妙的问题,App无法开机自动启动,这就要命了!
先后测试过多种版本的手机,也找过各种方案,最后找到原因所在:Android11和以上系统不支持非系统应用的自动启动!
找到原因就好办了,在网上搜索个方法,能用系统悬浮窗权限来绕过不能启动的限制

第一步:增加系统广告接收

class BootReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent?) {
        if (intent?.action == Intent.ACTION_BOOT_COMPLETED
            /*|| intent?.action == Intent.ACTION_MEDIA_MOUNTED
            || intent?.action == Intent.ACTION_MEDIA_UNMOUNTED*/) {
            println("----------> Boot completed")
            Toast.makeText(context, "开始启动闸门控制程序:" + intent.action, Toast.LENGTH_LONG).show();

            val newIntent = Intent(context, MainActivity::class.java)
            newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(newIntent)
        }
    }
}

第二步:增加系统权限

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

第三步:增加广播注册

        <receiver
            android:name=".BootReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MEDIA_MOUNTED"/>
                <action android:name="android.intent.action.MEDIA_UNMOUNTED"/>
                <data android:scheme="file" />
            </intent-filter>
            <intent-filter android:priority="1000">
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </receiver>

第四步:申请权限

MainActivity 中增加

    override fun onResume() {
        super.onResume()
        if (!Settings.canDrawOverlays(this)) {
            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
            intent.data = Uri.parse("package:$packageName")
            startActivity(intent)
        }
    }

第五步:如何时使用

这样处理完成后在App启时发现没有权限动会跳到权限设置界面,打开允许显示在系统应用最上层权限就行了。
这里流氓了一点,不给权限是不让进系统的。

路灯

这个人很懒,什么都没留下

文章评论