检查Activity是否从Service运行

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)

  • 值得注意的是,您需要在清单中添加`<uses-permission android:name ="android.permission.GET_TASKS"/>`以使其正常工作. (15认同)
  • `GET_TASK`现已弃用. (6认同)
  • 这个答案是针对包装的.但问题是关于Activity,如果条件必须检查componentInfo.getClassName(). (3认同)
  • API 21中不推荐使用此方法https://developer.android.com/reference/android/app/ActivityManager.html#getRunningTasks(int) (2认同)
  • 使用`REAL_GET_TASKS`而不是. (2认同)
  • 我认为这会有帮助。删除了所有已弃用的方法。http://stackoverflow.com/a/32472091/1318946 (2认同)

eir*_*ran 9

使用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,因为有时它会直接跳到o​​nDestroy :)它基本上都是伏都教

无论如何,希望能有所帮助

  • 谢谢@eiran.这是我发现有效的唯一解决方案. (2认同)

Com*_*ler 6

从Lollipop开始,getRunningTasks不推荐使用:

 * <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.
Run Code Online (Sandbox Code Playgroud)

一种方法是在app start上绑定到服务.然后:1.如果您需要检查应用程序的任何活动是否正在运行,您可以为您的活动创建基类并覆盖onPause和onResume.在onPause中,调用服务方法让它知道它在后台.在onResume中,调用一个服务方法让它知道它在前台.2.如果您只需要对某些特定活动执行此操作,只需在这些活动上覆盖onResume和onPause,或为这些活动创建基本活动.