Solution to the inability to apply for SYSTEM_ALERT_WINDOW permission on Android M

Recently, I was working on a project that required adapting the secondary screen display function of each machine, which covers various versions of Android 5.0 and above. If you want to know more about the Android secondary screen function, you can refer to this article:

AndroidPresentation

Simply put, using the secondary screen in Android requires the use of the Presentation class. To ensure that the secondary screen can be displayed globally, the context object Context passed first can be from Application or Service , and the SYSTEM_ALERT_WINDOW permission needs to be additionally enabled .

Since Android 6.0 and above require dynamic application for permissions, SYSTEM_ALERT_WINDOW is special and cannot be applied directly through the code ActivityCompat.requestPermissions . Then you need to indirectly guide the user to the settings page to prompt the user for authorization:
The settings interface displayed on the upper layer of the application
the reference code is as follows:

//参考自http://stackoverflow.com/questions/32061934/permission-from-manifest-doesnt-work-in-android-6
public static int OVERLAY_PERMISSION_REQ_CODE = 1234;

@TargetApi(Build.VERSION_CODES.M)
public void requestDrawOverLays() {
    
    
    if (!Settings.canDrawOverlays(MainActivity.this)) {
    
    
        Toast.makeText(this, "您还没有打开悬浮窗权限", Toast.LENGTH_SHORT).show();
        //跳转到相应软件的设置页面
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + MainActivity.this.getPackageName()));
        startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
    } else {
    
    
      // 授权成功之后执行的方法
      ...
    }
}

@TargetApi(Build.VERSION_CODES.M)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
    
    if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
    
    
        if (!Settings.canDrawOverlays(this)) {
    
    
            Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
        } else {
    
    
            Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
        }
    }
}

Guess you like

Origin blog.csdn.net/liuzhuo13396/article/details/120040459