绘制覆盖权限仅在第一次安装应用程序时询问

Draw Overlay permission only asks first time when app is installed

我正在开发音乐播放器应用程序。其中,当应用程序最小化(暂停)时,我想在屏幕上为 play/pause 事件显示一个小的浮动按钮。 (功能类似于face book messenger聊天头)。它在 SDK < 23 的设备上运行良好。但在 SDK >= 23 的设备中,它仅在安装应用程序时第一次请求许可。

如果允许,它也可以完美显示浮动按钮。但是一旦应用程序关闭并再次启动,它就不再显示浮动按钮了。

我打开权限对话框的代码是:

public final static int REQUEST_CODE = 100;

public void checkDrawOverlayPermission() {
    /** check if we already  have permission to draw over other apps */
    if (!Settings.canDrawOverlays(this)) {
        /** if not construct intent to request permission */
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:" + getPackageName()));
        /** request permission via start activity for result */
        startActivityForResult(intent, REQUEST_CODE);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode,  Intent data) {
    /** check if received result code
     is equal our requested code for draw permission  */
    if (requestCode == REQUEST_CODE) {

        if (Settings.canDrawOverlays(this)) {
            // continue here - permission was granted
            if(isServiceRunning != true){
                isServiceRunning = true;
                intent12 = new Intent(this,  notificationService.class);
                bindService(intent12, notificationConnection, Context.BIND_AUTO_CREATE);
                startService(intent12);
            }
        }
    }
}

我在应用程序暂停时显示浮动按钮(当按下主页按钮或后退按钮以最小化应用程序时)。所以我在我的应用程序 mainActivity 的 onPause() 方法中调用这个 checkDrawOverlayPermission() 方法,如下所示:

    @Override
protected void onPause() {
    super.onPause();
    if (Build.VERSION.SDK_INT >= 23) {
        checkDrawOverlayPermission();
    } else {
        if(isServiceRunning != true){
            isServiceRunning = true;
            intent12 = new Intent(this,  notificationService.class);
            bindService(intent12, notificationConnection, Context.BIND_AUTO_CREATE);
            startService(intent12);
        }
    }
}

但我不明白我在这里错过了什么。我认为检查权限的代码是可以的,因为它第一次在屏幕上显示浮动按钮以及在一个小对话框中请求权限。请帮忙。谢谢!

如果权限已在 SDK > 23 中授予,则您无需执行任何操作。 像这样向 checkDrawOverlayPermission 方法添加一个 else 部分。

public void checkDrawOverlayPermission() {
    /** check if we already  have permission to draw over other apps */
    if (!Settings.canDrawOverlays(this)) { // WHAT IF THIS EVALUATES TO FALSE.
        /** if not construct intent to request permission */
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:" + getPackageName()));
        /** request permission via start activity for result */
        startActivityForResult(intent, REQUEST_CODE);
    } else { // ADD THIS.
        // Add code to bind and start the service directly.
    }
}