Check whether activity is active
There might be an easier way I can't think of but one way is to implement it yourself. On onResume()
you set a member variable mIsRunning
to true and on onPause()
back to false. Using this boolean you should know not to call alert.show()
on your callback.
ArrayList<String> runningactivities = new ArrayList<String>();
ActivityManager activityManager = (ActivityManager)getBaseContext().getSystemService (Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> services = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (int i1 = 0; i1 < services.size(); i1++) {
runningactivities.add(0,services.get(i1).topActivity.toString());
}
if(runningactivities.contains("ComponentInfo{com.app/com.app.main.MyActivity}")==true){
Toast.makeText(getBaseContext(),"Activity is in foreground, active",1000).show();
alert.show()
}
This way you will know if the pointed activity is the current visible activity, else your alert will not display.
This will only work when we navigate between two activities without finish.
This happens when the Activity will be going through its destruction when the background thread finishes its work and tries to show a Dialog.
This exeption is rare to reproduce but happens when we do some async task / background operation and want to display a dialog with Activity context and in the mean while our activity is destroying itself due to some reason.
Android OS should handle this situation, but as of now it does not.
so before calling your dialog just check if activity is running and not in its destruction phase.
if(!isFinishing()){
callDialog();
}
Background thread after finishing their networking tasks invokes callback onSuccess()/onFailure() on the main thread. And if at that time, the activity which initiated this background thread task is not in the foreground and you try to use getActivity() in either onSuccess()/onFailure(), it will give you the exception. So try to add this check before doing any UI operation.
if(!((Activity) context).isFinishing())
{
//show alert
}