【Android】【Bug】Android 11 不能开机自启动的解决方法

项目需求

在Android 11 版本上面实现程序的开机自启动

需求实现

1.创建一个广播

public class BootReceiver extends BroadcastReceiver {
    
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
    
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
    
    
            Intent bootStart = new Intent(context, WelcomeActivity.class);
            bootStart.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(bootStart);
        }
    }
}

2.在清单文件注册

        <receiver
            android:name=".receiver.BootReceiver"
            android:enabled="true"
            android:exported="true"
            android:permission="android.permission">
            <intent-filter android:priority="2147483647">
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

记得添加权限

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

然后我们去测试,在低版本Android 系统上面测试之后,OK没问题,那在Android 11 上面测试呢?

答案是根本无法开机启动

那怎么解决呢?

需要给我们的程序请求一个权限,这个权限如果我们在做应用显示悬浮窗之类的功能也会用到,就像微信视频通话的那种小窗显示之类的。

        if (Build.VERSION.SDK_INT >= 23) {
    
    
            if (!Settings.canDrawOverlays(this)) {
    
    
                //没有悬浮窗权限,去开启悬浮窗权限
                try {
    
    
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                    startActivityForResult(intent, 101);
                } catch (Exception e) {
    
    
                    e.printStackTrace();
                }
            } 
        }

就是这个权限
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43358469/article/details/141346447