我有一个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 --;
}
}
我也注册了在应用程序类中创建
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ApplicationLifeCycleManager());
}
但是当我在活动之间切换时会调用 onPaused 和 onResumed 和 onDestroyed 函数:因为它检测是否有任何活动被关闭或销毁甚至恢复
所以有任何解决方案来检查应用程序是否在一个功能中关闭?