
Declare the following method named isAppInForeground() in your activity:
//---helper method to
determine if the app is in the
// foreground---
public static boolean
isAppInForeground(Context context) {
List
tasks =
((ActivityManager)
context.getSystemService(
Context.ACTIVITY_SERVICE))
.getRunningTasks(1);
if
(tasks.isEmpty()) {
return false;
}
return tasks
.get(0)
.topActivity
.getPackageName()
.equalsIgnoreCase(context.getPackageName());
}
In order for the method to work, you need to add the GET_TASKS permission in your AndroidManifest.xml file:
<uses-permission
android:name="android.permission.GET_TASKS"/ >
To check if your app is in the foreground, simply call the isAppInForeground() method:
if (isAppInForeground(getApplicationContext()))
{
Toast.makeText(this,
"App is in the foreground",
Toast.LENGTH_LONG).show();
} else {
//---create
notifications, etc---
}
If the apps is in the background, you might want to create a
notifications, etc, to inform the user.
No comments:
Post a Comment