0

我的 Android 应用程序中有这个代码片段,用于检查应用程序是否被杀死。

    static boolean isAppKilled(Context appContext) {
        boolean appProcessRunning = false;

        ActivityManager activityManager = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses != null) {
            String packageName = appContext.getPackageName();
            for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
                System.out.println("LM:appProcess: " + appProcess.processName);
                System.out.println("LM:appProcess: " + appProcess.importance);
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE &&
                        appProcess.processName.equals(packageName)) {
                    appProcessRunning = true;
                    break;
                }
            }
        }

        return appProcessRunning;
    }

但是,这个片段也为后台的应用程序返回“true”,这不是有意的。

在此处输入图像描述

你们中的任何人都可以为我提供一个代码片段来满足上述所有情况吗?

4

1 回答 1

0

您可以LifecycleObserver在您的类中实现接口Application并实现生命周期方法:

 class YourApp : Application, LifecycleObserver {
    
        override fun onCreate() { ....}
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun onAppInForeground {
            //do some logic to handle onForeground event.
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun onAppInBackground {
                //do some logic to handle onBackground event.
            }
        }

但是您需要将依赖项添加到您的 gradle 文件中:

// ProcessLifecycleOwner provides a lifecycle for the whole application process
  implementation("androidx.lifecycle:lifecycle-process:$lifecycle_version")

有关更多信息,请查看链接: https ://developer.android.com/topic/libraries/architecture/lifecycle

于 2021-06-30T11:01:28.953 回答