Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if Android app is running in the foreground?

I am doing a status bar notification in my android app that is triggered by c2dm. I don't want to display the notification if the app is running. How do you determine if the app is running and is in the foreground?

like image 736
Andrew Thomas Avatar asked Mar 31 '11 18:03

Andrew Thomas


People also ask

How do I know if an app is running in the foreground?

Whenever a new activity is started and visible to the user its instance is updated in the application class: activeActivity variable, so we can use it to determine which activity is in the foreground from the notifications layer.

How do I know if an app is running in the background Android?

You can detect currently foreground/background application with ActivityManager. getRunningAppProcesses() which returns a list of RunningAppProcessInfo records. To determine if your application is on the foreground check RunningAppProcessInfo.


2 Answers

Alternately, you can check with the ActivityManager what tasks are running by getRunningTasks method. Then check with the first task(task in the foreground) in the returned List of tasks, if it is your task.
Here is the code example:

public Notification buildNotification(String arg0, Map<String, String> arg1) {      ActivityManager activityManager = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);     List<RunningTaskInfo> services = activityManager             .getRunningTasks(Integer.MAX_VALUE);     boolean isActivityFound = false;      if (services.get(0).topActivity.getPackageName().toString()             .equalsIgnoreCase(appContext.getPackageName().toString())) {         isActivityFound = true;     }      if (isActivityFound) {         return null;     } else {         // write your code to build a notification.         // return the notification you built here     }  } 

And don't forget to add the GET_TASKS permission in the manifest.xml file in order to be able to run getRunningTasks() method in the above code:

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

p/s : If agree this way, please to note that this permission now is deprecated.

like image 104
Gadenkan Avatar answered Oct 06 '22 19:10

Gadenkan


Make a global variable like private boolean mIsInForegroundMode; and assign a false value in onPause() and a true value in onResume().

Sample code:

private boolean mIsInForegroundMode;  @Override protected void onPause() {     super.onPause();     mIsInForegroundMode = false; }  @Override protected void onResume() {     super.onResume();     mIsInForegroundMode = true; }  // Some function. public boolean isInForeground() {     return mIsInForegroundMode; } 
like image 27
Wroclai Avatar answered Oct 06 '22 19:10

Wroclai