Tar*_*nfx 42 android android-service android-activity
如何Service检查其中一个应用程序Activity是否在前台运行?
Ras*_*sel 62
将以下方法与您的包名称一起使用.如果您的任何活动在前台,它将返回true.
public boolean isForeground(String myPackage) {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1);
ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
return componentInfo.getPackageName().equals(myPackage);
}
Run Code Online (Sandbox Code Playgroud)
添加权限:
<uses-permission android:name="android.permission.GET_TASKS" />
Run Code Online (Sandbox Code Playgroud)
使用SharedPreferences在onResume,onPause等中保存应用的状态.
像这样:
@Override
public void onPause() {
super.onPause();
PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("isActive", false).commit();
}
@Override
public void onDestroy() {
super.onDestroy();
PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("isActive", false).commit();
}
@Override
public void onResume() {
super.onResume();
PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("isActive", true).commit();
}
Run Code Online (Sandbox Code Playgroud)
然后在服务中:
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("isActive", false)) {
return;
}
Run Code Online (Sandbox Code Playgroud)
我同时使用onPause和onDestroy,因为有时它会直接跳到onDestroy :)它基本上都是伏都教
无论如何,希望能有所帮助
从Lollipop开始,getRunningTasks不推荐使用:
Run Code Online (Sandbox Code Playgroud)* <p><b>Note: this method is only intended for debugging and presenting * task management user interfaces</b>. This should never be used for * core logic in an application, such as deciding between different * behaviors based on the information found here.</p> * * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method * is no longer available to third party applications.
一种方法是在app start上绑定到服务.然后:1.如果您需要检查应用程序的任何活动是否正在运行,您可以为您的活动创建基类并覆盖onPause和onResume.在onPause中,调用服务方法让它知道它在后台.在onResume中,调用一个服务方法让它知道它在前台.2.如果您只需要对某些特定活动执行此操作,只需在这些活动上覆盖onResume和onPause,或为这些活动创建基本活动.
| 归档时间: |
|
| 查看次数: |
33468 次 |
| 最近记录: |