Android检查应用程序是否关闭

Ama*_*alo 0 android android-lifecycle android-activity android-activitymanager

我有一个android应用程序,我需要一个功能或任何广播接收器,可以检查应用程序是否关闭。.我不需要在每个活动中调用destroy(该应用程序中大约有20个活动)应用程序类中的功能

public class ApplicationLifeCycleManager implements ActivityLifecycleCallbacks {

/** Manages the state of opened vs closed activities, should be 0 or 1.
 * It will be 2 if this value is checked between activity B onStart() and
 * activity A onStop().
 * It could be greater if the top activities are not fullscreen or have
 * transparent backgrounds.
 */
private static int visibleActivityCount = 0;

/** Manages the state of opened vs closed activities, should be 0 or 1
 * because only one can be in foreground at a time. It will be 2 if this
 * value is checked between activity B onResume() and activity A onPause().
 */
private static int foregroundActivityCount = 0;

/** Returns true if app has foreground */
public static boolean isAppInForeground(){
    return foregroundActivityCount > 0;
}

/** Returns true if any activity of app is visible (or device is sleep when
 * an activity was visible) */
public static boolean isAppVisible(){
    return visibleActivityCount > 0;
}

public void onActivityCreated(Activity activity, Bundle bundle) {
}

public void onActivityDestroyed(Activity activity) {
    Log.wtf("destroyed","app closed!!");
}

public void onActivityResumed(Activity activity) {
    foregroundActivityCount ++;
}

public void onActivityPaused(Activity activity) {
    foregroundActivityCount --;
}

public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}

public void onActivityStarted(Activity activity) {
    visibleActivityCount ++;
}

public void onActivityStopped(Activity activity) {
    visibleActivityCount --;
}
}
Run Code Online (Sandbox Code Playgroud)

我也已经在Application类中注册了create

@Override
public void onCreate() {
    super.onCreate();
    registerActivityLifecycleCallbacks(new ApplicationLifeCycleManager());
}
Run Code Online (Sandbox Code Playgroud)

但是当我在活动之间切换时会调用onPaused和onResumed和onDestroyed函数:因为它检测是否关闭了任何活动或破坏了活动,甚至恢复了活动

所以任何解决方案,以检查该应用程序是否在一个功能中关闭?

小智 6

您可以使用此功能来确定该应用程序是否已关闭(不在后台或在前台)。

private boolean isAppRunning() {
    ActivityManager m = (ActivityManager) this.getSystemService( ACTIVITY_SERVICE );
    List<ActivityManager.RunningTaskInfo> runningTaskInfoList =  m.getRunningTasks(10);
    Iterator<ActivityManager.RunningTaskInfo> itr = runningTaskInfoList.iterator();
    int n=0;
    while(itr.hasNext()){
        n++;
        itr.next();
    }
    if(n==1){ // App is killed
        return false;
    }

    return true; // App is in background or foreground
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用以下功能检查应用程序是否在前台:https : //stackoverflow.com/a/8490088/9005188


S.R*_*S.R 6

该答案使用ProcessLifecycleOwner来检测应用程序可见性。

这是Android Architecture Component的一部分。


1.将此库添加到您的项目

implementation "android.arch.lifecycle:extensions:1.1.1"

2.扩展实现LifecycleObserver的应用程序类

public class AppController extends Application implements LifecycleObserver {


///////////////////////////////////////////////
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onEnterForeground() {
        Log.d("AppController", "Foreground");
        isAppInBackground(false);
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onEnterBackground() {
        Log.d("AppController", "Background");
        isAppInBackground(true);
    }
///////////////////////////////////////////////



    // Adding some callbacks for test and log
    public interface ValueChangeListener {
        void onChanged(Boolean value);
    }
    private ValueChangeListener visibilityChangeListener;
    public void setOnVisibilityChangeListener(ValueChangeListener listener) {
        this.visibilityChangeListener = listener;
    }
    private void isAppInBackground(Boolean isBackground) {
        if (null != visibilityChangeListener) {
            visibilityChangeListener.onChanged(isBackground);
        }
    }
    private static AppController mInstance;
    public static AppController getInstance() {
        return mInstance;
    }



    @Override
    public void onCreate() {
        super.onCreate();

        mInstance = this;

        // addObserver
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    }

}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

AppController.getInstance().setOnVisibilityChangeListener(new ValueChangeListener() {
    @Override
    public void onChanged(Boolean value) {
        Log.d("isAppInBackground", String.valueOf(value));
    }
});
Run Code Online (Sandbox Code Playgroud)

不要忘记将应用程序添加name到您的manifest

<application
    android:name="myPackageName.AppController"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"">
Run Code Online (Sandbox Code Playgroud)

做完了


(Kotlin示例)

https://github.com/jshvarts/AppLifecycleDemo


Ari*_*Roy 2

基本上看看你的问题,你想跟踪应用程序中的状态变化。

正确处理所有用例可能非常困难。但是有一个令人惊叹的库,它运行得很好并且非常易于使用- RxAppState

我已经使用这个库很长一段时间了,它在所有情况下都工作得很好。我强烈推荐你尝试一下这个。

  • **已弃用** .....[ProcessLifecycleOwner](https://developer.android.com/reference/android/arch/lifecycle/ProcessLifecycleOwner) 它是 [Android 架构组件](https://developer .android.com/topic/libraries/architecture)是首选。演示 ProcessLifecycleOwner 用法的 kotlin 示例项目位于[此处](https://github.com/jshvarts/AppLifecycleDemo) (3认同)