Analysis on the Pit of Pop up Dialog Box in Android Service

  • 2021-11-30 01:39:06
  • OfStack

1. Mobile phone version problem, most articles do not cover this point, resulting in their code can not be used normally

Type required above M version-- > TYPE_APPLICATION_OVERLAY


AlertDialog.Builder builder=new AlertDialog.Builder(getApplicationContext()); 
builder.setTitle(" Prompt "); 
builder.setMessage("service Bullet frame "); 
builder.setNegativeButton(" Got it ",null); 
Dialog dialog=builder.create();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){//6.0         
  dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);            
}else {         
  dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);            
} 
dialog.show();

At the same time, because different versions of Android systems are involved,

It is stated in AndroidManifest. xml that permissions corresponding to both types are required


 <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
  <uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />

2. Permission problem, the pop-up dialog box in service is a system pop-up box, and you need to apply for floating window permission above M version

Suspended windows were allowed by default before Android 6.0

Pay attention to the use after Android 6.0

Because floating window permissions SYSTEM_ALERT_WINDOW It belongs to special authority and needs to apply separately

Special permissions, as the name implies, are 1 special sensitive permissions. In Android system, there are mainly two

SYSTEM_ALERT_WINDOW (set up a floating window and carry out some black technology)
WRITE_SETTINGS (Modify System Settings)

With regard to the authorization of the above two special permissions, the method is to use startActivityForResult to start the authorization interface.

Application method:


private static final int REQUEST_CODE = 1;
private void requestAlertWindowPermission() {
  Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
  intent.setData(Uri.parse("package:" + getPackageName()));
  startActivityForResult(intent, REQUEST_CODE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if (requestCode == REQUEST_CODE) {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
       if (Settings.canDrawOverlays(this)) {
                      Log.i("xqxinfo", "onActivityResult granted");
                       }
             } 
        } 
}

Summarize


Related articles: