I have a broadcast receiver, which launches a service, and in this service I should check, if my main application is active, or in background. Are there any methods how to do this?
Asked
Active
Viewed 143 times
3 Answers
2
You can extend the Application class and store the current state of your application. You will need to update it from every Activity's onPause() and onResume() methods.
public class MyApplication extends Application {
public static boolean isAppVisible() {
return visible;
}
public static void inForeground() {
visible = true;
}
public static void inBackground() {
visible = false;
}
private static boolean visible;
}
Register your application class in AndroidManifest.xml:
<application
android:name="your.app.package.MyApplication"
android:icon="@drawable/icon"
android:label="@string/app_name" >
Add onPause and onResume to every Activity in the project (you may create a common superclass for your Activities if you'd like to, but if your activity is already extended from MapActivity/ListActivity etc. you still need to write the following by hand):
@Override
protected void onResume() {
super.onResume();
MyApplication.inBackground();
}
@Override
protected void onPause() {
super.onPause();
MyApplication.inForeground();
}

Raghav Sood
- 81,899
- 22
- 187
- 195
0
Context ctx = context.getApplicationContext();
ActivityManager am = (ActivityManager) context
.getSystemService(ACTIVITY_SERVICE);
// get the info from the currently running task
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
PackageManager pm = this.getPackageManager();
boolean flag = false;
try {
/**
* take fore ground activity name
*/
ComponentName componentInfo = taskInfo.get(0).topActivity;
if (printLog) {
Log.d("Tag", "CURRENT Activity ::"
+ taskInfo.get(0).topActivity.getClassName());
Log.d("Tag", "Number Of Activities : "
+ taskInfo.get(0).numRunning);
Log.d("Tag",
"Componenet Info : " + componentInfo.getPackageName());
Log.d("Tag",
"Componenet Info : " + componentInfo.getClassName());
}
/**
* All activities name of a package to compare with fore ground
* activity. if match found, no notification displayed.
*/
PackageInfo info = pm.getPackageInfo(
"com.package_name",
PackageManager.GET_ACTIVITIES);
ActivityInfo[] list = info.activities;
for (int i = 0; i < list.length; i++) {
Log.d("Tag","Activity : "+list[i].name);
if (list[i].name.equals(componentInfo.getClassName())) {
flag = true;
}
}
if(flag)
{
//activity is running
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
And take <uses-permission android:name="android.permission.GET_TASKS" />
permission in manifest.

Chintan Rathod
- 25,864
- 13
- 83
- 93
0
Considering implementing an application that keep track if the app goes front or back using onPause() and onResume().
Have a look at this solution.
Hope it helps.

Community
- 1
- 1

Lazy Ninja
- 22,342
- 9
- 83
- 103