新的方式从Android 10及以上版本开始是使用SYSTEM_ALERT_WINDOW权限。以下是操作步骤:
在AndroidManifest.xml文件中声明此权限。
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
在 onCreate 方法中,当按钮被点击时,调用一个辅助方法来显示一个对话框,这样如果用户选择允许权限,设备设置中的覆盖权限将会打开。请注意,此点击按钮仅供您了解如何调用权限。根据您的应用程序要求,您可以以任何方式调用它。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showMessageForFloatingPermission("To use this feature requires over lay permission");
}
});
}
下面是已声明的辅助方法吗?
private void showMessageForFloatingPermission(String message) {
new android.app.AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
checkFloatingPermission();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create()
.show();
}
public void checkFloatingPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityFloatingPermission.launch(intent);
}
}
}
ActivityResultLauncher<Intent> startActivityFloatingPermission = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
}else{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(MainActivity.this)) {
showMessageForFloatingPermission("To use this feature requires over lay permission");
}
}
}
}
});
一旦您按照上述代码进行了实现,您就可以从服务类启动任何活动。您的活动将以编程方式启动。
Intent intent = new Intent(this, MyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
基本上,这就是你可以做到的。它运行良好。顺便说一句,您可以根据自己的需求随意操纵此代码。希望这能帮到您!