【发布时间】:2016-04-06 04:11:27
【问题描述】:
我有一个要求,我需要检查应用程序是在后台运行还是被杀死。我的做法如下图所示。
ActivityManager am = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> alltasks = am.getRunningTasks(1);
for (ActivityManager.RunningTaskInfo aTask : alltasks) {
// Used to check for CALL screen
if (aTask.topActivity.getClassName().equals("com.android.phone.InCallScreen")
|| aTask.topActivity.getClassName().equals("com.android.contacts.DialtactsActivity")) {
// When user on call screen show a alert message
Toast.makeText(context, "Phone Call Screen.", Toast.LENGTH_LONG).show();
}
// Used to check for SMS screen
if (aTask.topActivity.getClassName().equals("com.android.mms.ui.ConversationList")
|| aTask.topActivity.getClassName().equals("com.android.mms.ui.ComposeMessageActivity")) {
// When user on Send SMS screen show a alert message
Toast.makeText(context, "Send SMS Screen.", Toast.LENGTH_LONG).show();
}
// Used to check for CURRENT example main screen
String packageName = "com.sap.rex.ui";
if (aTask.topActivity.getPackageName().equals(packageName)) {
isInBackground = false;
Toast.makeText(context, "Current Example Screen.", Toast.LENGTH_LONG).show();
}
上面的代码只是检查是否是top Activity包名,并判断它是否在后台。
如果我们在它上面打开两个或三个应用程序,因为它只取顶级应用程序包名,所以它说它不在后台,即使它在那里。
请让我知道我哪里做错了。
谢谢
【问题讨论】:
-
@Dhavalkumar Solanki 我会检查并告诉你
标签: android android-activity background-foreground