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