I'm having a problem with a listener in a certain activity.
The problem is that this listener contains an alert.show(); which can be called after we try to push a new activity (which then gives an exception).
e.g.: I'm listening in activity A for a signal from an other phone. I press back and try to run a new activity B but the program crashes because of the alert.show() A's listener.
ERROR/AndroidRuntime(3573): android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@476c21c0 is not valid; is your activity running?
Can I check in A's listener whether this activity is active and then show the alert or not depending on this value?
Check to see whether this activity is in the process of finishing, either because you called finish() on it or someone else has requested that it finished. This is often used in onPause() to determine whether the activity is simply pausing or completely finishing.
This example demonstrates How to get current activity name in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With