我有一个广播接收器,它启动一个服务,在这个服务中我应该检查,如果我的主应用程序是活动的,或在后台。有什么方法可以做到这一点吗?
答案 0 :(得分:2)
您可以扩展Application类并存储应用程序的当前状态。您需要从每个Activity的onPause()和onResume()方法更新它。
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;
}
在AndroidManifest.xml中注册您的应用程序类:
<application
android:name="your.app.package.MyApplication"
android:icon="@drawable/icon"
android:label="@string/app_name" >
将onPause和onResume添加到项目中的每个Activity(如果您愿意,可以为您的活动创建一个公共超类,但如果您的活动已经从MapActivity / ListActivity等扩展,您仍需要编写以下内容手工):
@Override
protected void onResume() {
super.onResume();
MyApplication.inBackground();
}
@Override
protected void onPause() {
super.onPause();
MyApplication.inForeground();
}
答案 1 :(得分: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();
}
并在清单中获得<uses-permission android:name="android.permission.GET_TASKS" />
权限。
答案 2 :(得分:0)
考虑实施一个应用程序,使用onPause()和onResume()来跟踪应用程序的正面或背面。
看看这个solution
希望它有所帮助。