Draw Overlay权限仅在第一次安装应用程序时询问

时间:2016-10-29 14:56:51

标签: java android android-6.0-marshmallow android-permissions

我正在开发音乐播放器应用程序。其中,我想在应用程序最小化(暂停)时在屏幕上显示一个小的浮动按钮,用于播放/暂停事件。 (功能像面书信使聊天头)。它适用于具有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的checkDrawOverlayPermission()方法中调用了这个onPause()方法,如下所示:

    @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);
        }
    }
}

但我无法理解我在这里失踪的东西。我认为检查权限的代码是可以的,因为它首次在屏幕上显示浮动按钮并在小对话中询问权限。请帮忙。谢谢!

1 个答案:

答案 0 :(得分:1)

如果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.
    }
}