Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether activity is active

Tags:

android

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?

like image 520
Vincent Avatar asked May 09 '11 07:05

Vincent


People also ask

How can I tell if activity has stopped?

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.

How can I get current activity?

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.


2 Answers

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.

like image 144
harism Avatar answered Sep 30 '22 22:09

harism


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.

like image 33
Samet Avatar answered Sep 30 '22 23:09

Samet