Reputation: 876
I am designing an android app which uses notification.
Before this, I was using a full screen activity, so if a notification came, in full view I didn't get any alert.
Now I am using a blank activity with notifications enabled.
I don't want to show notifications when I am already inside the app (like skype).
Or else, I want to cancel them immediately once flashed.
How to achieve this?
Thank you in advance.
Upvotes: 0
Views: 116
Reputation: 1433
You can try to get the running processes list and check if the one in foreground is your app.
private boolean isAppInForeground() {
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> mRunningProcesses = mActivityManager
.getRunningAppProcesses();
Iterator<RunningAppProcessInfo> i = mRunningProcesses.iterator();
while (i.hasNext()) {
RunningAppProcessInfo runningAppProcessInfo = i.next();
if (runningAppProcessInfo.uid == getApplicationInfo().uid && runningAppProcessInfo.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND)
{
return true;
}
}
return false;
}
Upvotes: 1
Reputation: 5020
You can define a superclass for all of your activities and track the state of the app. If all activities are in stopped state - app in the background, otherwise - in the foreground. In onStart()
and onStop()
methods of your super activity you can increment and decrement the number of visible activites.
public class SuperActivity extends Activity {
private static int sVisibleActivitiesCount;
@Override
public void onStart(){
super.onStart();
sVisibleActivitiesCount++;
}
@Override
public void onStop(){
super.onStart();
sVisibleActivitiesCount--;
}
public static boolean isAppInForeground() {
return sVisibleActivitiesCount > 0;
}
}
Now you can check somewhere for an application status and not create notification if SuperActivity.isAppInForeground
returns true.
The second approach is to use ActivityLifecycleCallbacks (min API 14) for monitoring activities lifecycle and track application state in a single place without having a super class for all activities. So I would rather use this approach if your app has minSdkVersion="14".
Upvotes: 2