Reputation: 64
I have an Application class that has a timer which is checking for login status.
If login status changes, that class logs out the current user from this device and before that it displays an AlertDialog
telling the user that app will log him out. In this class, I store current context, from which I can manipulate current activity.
Problem comes when I have an active AlertDialog
in any activity or fragment and my status changes and that logout dialog can't be shown and throws exception saying unable to add window.
Now my question is how could I check if any dialog is on top of current activity, and how can I force remove them all and show my logout dialog?
Upvotes: 1
Views: 229
Reputation: 1766
You need to have a global dialog instance. I will use a simple example to explain this. I have created a MainActivity
.
Inside it I have the
onCreate
- This will be called when your app starts.buildAlertDialog
- This will create one instance of the alert dialog.onStopMethod
- This will be called when the activity stops.onDestroy()
- This will be called when the application instance is destroyed by the OS.In the onCreate
method, you can check if the dialog is showing and close it and do somthing else.
I have added code to dismiss the dialog automatically when the activity stops.
import android.content.Context;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.ui.AppBarConfiguration;
import com.example.myapplication.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration appBarConfiguration;
private ActivityMainBinding binding;
private AlertDialog alertDialog;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext(); // Get application context
buildAlertDialog(context);
// To show the dialog do this
alertDialog.show();
// You can check if it showing then close it before you do something
if (alertDialog.isShowing()) {
alertDialog.dismiss(); // Dismiss
// Then do something
} else {}
}
private void buildAlertDialog(final Context context) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setCancelable(true);
alertDialogBuilder.setTitle("Sample AlertDialog");
alertDialogBuilder.setMessage("This is a sample AlertDialog to demonstrate global instance");
alertDialogBuilder.setNegativeButton("Close", (dialogInterface, i) -> {
});
alertDialog = alertDialogBuilder.create(); // Create dialog
}
@Override
public void onStop() {
super.onStop();
alertDialog.dismiss(); // Dismiss dialog onStop
}
@Override
public void onDestroy() {
super.onDestroy();
alertDialog.cancel(); // Dismiss dialog onDestroy
}
}
Upvotes: 1