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?
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.
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.
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.
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; }
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