Discovering if Android activity is running

codeScriber picture codeScriber · May 27, 2012 · Viewed 20.8k times · Source

I'm using C2DM, my BroadcastReceivers propagate the C2DM events to a local service. the service complete the registration by sending the id to my webserver pus it's responsible for letting the device know about new messages, however if the application (one of the activities) is up we want to send an intent to that activity with the new data so it can be updated, if not than the NotificationManager is used to notify the user.

The issue is, how to know the activity is running ? the Application object is not an option since the Service is part of the application it's obviously going to be present. unregister in the onDesroy of each application is also not an option since it may occur in orientation change...

Any standard way to get it done ?

Answer

ρяσѕρєя K picture ρяσѕρєя K · May 27, 2012

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!