我正在开发一个音乐播放器应用程序。在其中,我想在屏幕上显示一个小浮动按钮播放/暂停事件时,应用程序被最小化(暂停)。(功能像facebook 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);
}
}
}
}
当应用程序暂停时,我正在显示浮动按钮(当home按钮或后退按钮按下以最小化应用程序时)。所以我在我的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
方法中添加其他部分。
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.
}
}