我需要为我的应用程序打开叠加设置窗口。当然,我的清单文件已经使用了SYSTEM_ALERT_WINDOW权限。
public class MainActivity extends ReactActivity {
private static final int CODE_DRAW_OVER_OTHER_APP_PERMISSION = 2084;
@Override
protected String getMainComponentName() {
return "MyToolbox";
}
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new ReactActivityDelegate(this, getMainComponentName()) {
@Override
protected ReactRootView createRootView() {
return new RNGestureHandlerEnabledRootView(MainActivity.this);
}
};
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requireDrawOverlayPermission();
}
//Ask draw overlay permission
void requireDrawOverlayPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package: " + getPackageName()));
startActivityForResult(intent, CODE_DRAW_OVER_OTHER_APP_PERMISSION);
} else {
//TODO: Permission granted
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CODE_DRAW_OVER_OTHER_APP_PERMISSION) {
if (Settings.canDrawOverlays(this)) {
//TODO: Permission granted
} else {
Toast.makeText(this, "Draw over the app is not available", Toast.LENGTH_SHORT).show();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
从我的Android Studio运行的第一个调试,我的应用程序崩溃了。下次,它不会崩溃,但它不会为我显示叠加设置窗口。我可以看到屏幕闪烁但立即关闭。我的代码中有什么问题?谢谢!
终于,我终于想通了。该设置窗口需要包名称才能知道哪个应用需要此权限。并且 uri 无法解析我的包名称,因为我在"package:"和"getPackageName()"之间放了一个空格。我按如下方式删除了它,一切正常!
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));