If our app supports single sign-on and account kick out, a dialog will pop up when we receive a “need to kick out the current user” message from the back end of the push. The timing of such dialogs is uncertain. One way to do this is to make a system-level dialog, like the system Dialog in ANR, and keep it at the top of the screen forever.
Dialog dialog = new Dialog(this);
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialog.show();
Copy the code
TYPE_SYSTEM_ALERT is deprecated and permissions need to be added.
/ * *@deprecated* /
@Deprecated
public static final int TYPE_SYSTEM_ALERT = 2003;
Copy the code
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Copy the code
Another way to think about this requirement is to remember that the dialog build is strongly related to the activity. The solution is to always keep the current activity object, and when the screen is locked and the app exits to the background, empty the saved current activity.
First, hold the current activity object in the Application:
public class App extends Application {
private AppCompatActivity curActivity;
@Override
public void onCreate(a) {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityResumed(Activity activity) {
curActivity = (AppCompatActivity) activity;
}
@Override
public void onActivityPaused(Activity activity) {
curActivity = null; }}); }}Copy the code
Then, define the popup dialog method:
public class App extends Application {
private AppCompatActivity curActivity;
public void showDialog(String title, String message) {
if (curActivity == null) {
return; // Don't forget to nullify
}
EasyDialog.builder(curActivity)
.setTitle(title)
.setMessage(message)
.setPositiveButton("ok".null) .build() .show(curActivity.getSupportFragmentManager()); }}Copy the code
Finally, call showDialog() in application to complete the popover if needed:
((App) getApplication()).showDialog("Global popover"."Can pop up a dialog at any time")
Copy the code
The code here fetches the activity object in onResume() and onPause() to ensure that the current topmost activity is retrieved. When the app exits the background, the curActivity becomes null, and dialog boxes are no longer allowed. Finally, do something like nullating the activity or isDestroyed() on the pop-up to prevent the activity from being destroyed.
An aside:
When you support of the application of the function of split screen, which is more window, so you need to in onStop () to empty the activity, the onStart () in the activity, more details please refer to the multi-window support | Android Developers “.
@Override
public void onActivityStarted(Activity activity) {
curActivity = (AppCompatActivity) activity;
}
@Override
public void onActivityStopped(Activity activity) {
curActivity = null;
}
Copy the code