Android: How to Check If Activity Is Running

Android: how do I check if activity is running?

You can use a static variable within the activity.

class MyActivity extends Activity {
static boolean active = false;

@Override
public void onStart() {
super.onStart();
active = true;
}

@Override
public void onStop() {
super.onStop();
active = false;
}
}

The only gotcha is that if you use it in two activities that link to each other then onStop on the first is sometimes called after onStart in second. So both might be true briefly.

Depending on what you are trying to do (update the current activity from a service?). You could just register a static listener in the service in your activity onStart method then the correct listener will be available when your service wants to update the UI.

How to check if activity is in foreground or in visible background?

This is what is recommended as the right solution:

The right solution (credits go to Dan, CommonsWare and NeTeInStEiN)
Track visibility of your application by yourself using
Activity.onPause, Activity.onResume methods. Store "visibility" status
in some other class. Good choices are your own implementation of the
Application or a Service (there are also a few variations of this
solution if you'd like to check activity visibility from the service).

Example
Implement custom Application class (note the isActivityVisible() static method):

public class MyApplication extends Application {

public static boolean isActivityVisible() {
return activityVisible;
}

public static void activityResumed() {
activityVisible = true;
}

public static void activityPaused() {
activityVisible = false;
}

private static boolean activityVisible;
}

Register your application class in AndroidManifest.xml:

<application
android:name="your.app.package.MyApplication"
android:icon="@drawable/icon"
android:label="@string/app_name" >

Add onPause and onResume to every Activity in the project (you may
create a common ancestor for your Activities if you'd like to, but if
your activity is already extended from MapActivity/ListActivity etc.
you still need to write the following by hand):

@Override
protected void onResume() {
super.onResume();
MyApplication.activityResumed();
}

@Override
protected void onPause() {
super.onPause();
MyApplication.activityPaused();
}

In your finish() method, you want to use isActivityVisible() to check if the activity is visible or not. There you can also check if the user has selected an option or not. Continue when both conditions are met.

The source also mentions two wrong solutions...so avoid doing that.

Source: stackoverflow

Check if Activity is running from Service

Use the below method with your package name. It will return true if any of your activities is in foreground.

public boolean isForeground(String myPackage) {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1);
ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
return componentInfo.getPackageName().equals(myPackage);
}

Update:

Add Permission:

<uses-permission android:name="android.permission.GET_TASKS" />

How to check if my activity is the current activity running in the screen

When your Activity comes to the foreground, its onResume() method will be invoked. When another Activity comes in front of your Activity, its onPause() method will be invoked. So all you need to do is implement a boolean indicating if your Activity is in the foreground:

private boolean isInFront;

@Override
public void onResume() {
super.onResume();
isInFront = true;
}

@Override
public void onPause() {
super.onPause();
isInFront = false;
}

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.

Discovering if Android activity is running

Solution 1:
You can use ActivityManager for Checking if Activity is Running or not:

public boolean isActivityRunning() { 

ActivityManager activityManager = (ActivityManager)Monitor.this.getSystemService (Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> activitys = activityManager.getRunningTasks(Integer.MAX_VALUE);
isActivityFound = false;
for (int i = 0; i < activitys.size(); i++) {
if (activitys.get(i).topActivity.toString().equalsIgnoreCase("ComponentInfo{com.example.testapp/com.example.testapp.Your_Activity_Name}")) {
isActivityFound = true;
}
}
return isActivityFound;
}

need to add the permission to your manifest..

<uses-permission  android:name="android.permission.GET_TASKS"/>

Solution 2:
Your can use an static variable in your activity for which you want to check it's running or not and store it some where for access from your service or broadcast receiver as:

static boolean CurrentlyRunning= false;
public void onStart() {
CurrentlyRunning= true; //Store status of Activity somewhere like in shared //preference
}
public void onStop() {
CurrentlyRunning= false;//Store status of Activity somewhere like in shared //preference
}

I hope this was helpful!

How to check if any activity is running?

Determining if your Android Application is in Background or Foreground is the most reliable method that I have come across. As explained in that article and elsewhere there are lot's of different ways for doing this, but using Application.ActivityLifecycleCallbacks as described is usually very reliable. It keeps count of number of activities started and if the number is greater than 1, your app is in the foreground.

How to check if an activity is the last one in the activity stack for an application?

UPDATE (Jul 2015):

Since getRunningTasks() get deprecated, from API 21 it's better to follow raukodraug answer or Ed Burnette one (I would prefer second one).



There's possibility to check current tasks and their stack using ActivityManager.

So, to determine if an activity is the last one:

  • request android.permission.GET_TASKS permissions in the manifest.
  • Use the following code:

    ActivityManager mngr = (ActivityManager) getSystemService( ACTIVITY_SERVICE );

    List<ActivityManager.RunningTaskInfo> taskList = mngr.getRunningTasks(10);

    if(taskList.get(0).numActivities == 1 &&
    taskList.get(0).topActivity.getClassName().equals(this.getClass().getName())) {
    Log.i(TAG, "This is last activity in the stack");
    }

Please note, that above code will be valid only if You have single task. If there's possibility that number of tasks will exist for Your application - You'll need to check other taskList elements. Read more about tasks Tasks and Back Stack


Android AsyncTasks How to Check If activity is still running

You can cancel your asynctask in the activity's onDestroy

@Override
protected void onDestroy() {
asynctask.cancel(true);
super.onDestroy();
}

and when performing changes you check whether your asynctask has been cancelled(activity destroyed) or not

protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
if(!isCancelled()) {
gender.setText(values[0]);
}
}


Related Topics



Leave a reply



Submit