gpt4 book ai didi

java - 所有 Activity 开始之前和所有 Activity 停止之后的监听器?

转载 作者:行者123 更新时间:2023-12-02 12:14:28 25 4
gpt4 key购买 nike

如果我想在任何 Activity 开始之前和所有 Activity 停止之后运行一些脚本,我应该在android中哪里放置这样的监听器?

我考虑过将其放入 Android Application 类中,并简单地将方法放入其 onCreateonSaveInstanceState 中 - 但我不确定他们在所有 Activity 之前和之后都会接到电话

最佳答案

不幸的是,在应用程序类中,当应用程序停止时没有回调,但我认为您可以尝试以下代码:

<<这是旧>

更新:Application类代码:

public class MyApplication extends Application {

@Override
public void onCreate() {
super.onCreate();
startService(new Intent(this, Monitor.class));
}
}

后台服务代码:

public class Monitor extends Service implements Application.ActivityLifecycleCallbacks {

private static final String TAG = "Monitor";

int mActivitiesCount = 1; // At the moment when service started, the main Activity is already opened

public Monitor() {
}

@Override
public void onCreate() {
super.onCreate();
getApplication().registerActivityLifecycleCallbacks(this);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}

@Override
public void onDestroy() {
getApplication().unregisterActivityLifecycleCallbacks(this);
super.onDestroy();
}

@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
mActivitiesCount++;
Log.d(TAG, "onActivityCreated: count: " + mActivitiesCount);
}

@Override
public void onActivityStarted(Activity activity) {

}

@Override
public void onActivityResumed(Activity activity) {

}

@Override
public void onActivityPaused(Activity activity) {

}

@Override
public void onActivityStopped(Activity activity) {

}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

}

@Override
public void onActivityDestroyed(Activity activity) {
mActivitiesCount--;
Log.d(TAG, "onActivityDestroyed: count: " + mActivitiesCount);
if (mActivitiesCount == 0) {
Log.d(TAG, "All activities was destroyed");
// do something
}
}

@Override
public IBinder onBind(Intent intent) {
return null;
}
}

关于java - 所有 Activity 开始之前和所有 Activity 停止之后的监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46290988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com