Reputation: 2792
I have implemented Push Notifications in my application. when i receive a message i have to check if the app is in background because if the app is not in background i have to open the application or else do nothing.
I have been using the below code but this is not working.
public static boolean isApplicationSentToBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
I have used the below permission also.
<uses-permission android:name="android.permission.GET_TASKS" />
But the above code is not working.
I cannot make use of OnStart()
and OnDestroy()
because i have many Activities in my application.
Is there any other to know if the app is in background.
Thanks
Upvotes: 0
Views: 80
Reputation: 286
One way is to create a flag to keep track of the foreground state yourself. This flag is set to false when onPause() is called, and set to true when onResume() is called. After the flag is set properly, you can use it to determine your action in the rest of part of your activity.
Upvotes: 0
Reputation: 231
if the app is not in background i have to open the application or else do nothing.
Use LocalBroadcastManager
- Link.
Register your activity as a receiver for the broadcast in onResume()
and unregister it in onPause()
.
Send a broadcast when a push notification is received. If your app is in foreground, it will receive the broadcast and deal with it accordingly - else, nothing.
Upvotes: 0
Reputation: 3823
Here is a previous question/answer. It's for checking in the background, but you could just as easily check the foreground.
Checking if an Android application is running in the background
Upvotes: 1