我有一个安卓应用程序,我需要一个函数或者任何广播接收器,可以检查这个应用程序是否被关闭。我不需要在每个活动中调用on destroy(该应用程序中有大约20个活动)我试图在Application类中添加这个函数。
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 --;
}
}
我还在应用程序类中注册了onCreate。
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ApplicationLifeCycleManager());
}
但是在我切换活动时,onPaused、onResumed和onDestroyed函数会被调用:因为它检测任何活动是否关闭、销毁甚至恢复。
那么有没有一种解决方案可以在一个函数中检查应用程序是否关闭?