通过背景,我的意思是应用程序的 Activity 当前对用户都不可见?
检测您的应用程序是否在后台运行的方法很少,但只有其中一种是完全可靠的:
Activity.onPause
自行跟踪应用程序的可见性, Activity.onResume
方法。将“可见性”状态存储在其他类中。不错的选择是您自己实现 Application
或 Service
(如果您想检查服务的 Activity 可见性,也有此解决方案的 a few variations)。Application
类(注意 isActivityVisible()
静态方法):public class MyApplication extends Application {
public static boolean isActivityVisible() {
return activityVisible;
}
public static void activityResumed() {
activityVisible = true;
}
public static void activityPaused() {
activityVisible = false;
}
private static boolean activityVisible;
}
AndroidManifest.xml
中注册您的应用程序类:<application
android:name="your.app.package.MyApplication"
android:icon="@drawable/icon"
android:label="@string/app_name" >
onPause
和 onResume
给每个 Activity
在项目中(如果您愿意,可以为您的 Activity 创建一个共同的祖先,但如果您的 Activity 已经从 MapActivity
/ListActivity
等扩展,您仍然需要手动编写以下内容):@Override
protected void onResume() {
super.onResume();
MyApplication.activityResumed();
}
@Override
protected void onPause() {
super.onPause();
MyApplication.activityPaused();
}
You can detect currently foreground/background application with
ActivityManager.getRunningAppProcesses()
which returns a list ofRunningAppProcessInfo
records. To determine if your application is on the foreground checkRunningAppProcessInfo.importance
field for equality toRunningAppProcessInfo.IMPORTANCE_FOREGROUND
whileRunningAppProcessInfo.processName
is equal to your application package name.Also if you call
ActivityManager.getRunningAppProcesses()
from your application UI thread it will return importanceIMPORTANCE_FOREGROUND
for your task no matter whether it is actually in the foreground or not. Call it in the background thread (for example viaAsyncTask
) and it will return correct results.
These APIs are not there for applications to base their UI flow on, but to do things like show the user the running apps, or a task manager, or such.
Yes there is a list kept in memory for these things. However, it is off in another process, managed by threads running separately from yours, and not something you can count on (a) seeing in time to make the correct decision or (b) have a consistent picture by the time you return. Plus the decision about what the "next" activity to go to is always done at the point where the switch is to happen, and it is not until that exact point (where the activity state is briefly locked down to do the switch) that we actually know for sure what the next thing will be.
And the implementation and global behavior here is not guaranteed to remain the same in the future.
ActivityManager.getRunningTasks
为其isApplicationBroughtToBackground
方法。请参阅上面 Dianne 的评论,也不要使用该方法。 关于android - 检查Android应用程序是否在后台运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3667022/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) | Powered by Discuz! X3.4 |