当前,我正在使用androidx.lifecycle.DefaultLifecycleObserver
在应用程序“退出”时执行一些代码。我如何定义“退出”
onPause
个主要活动。这样,我使用以下方式捕获“退出”事件。
public class WeNoteApplication extends MultiDexApplication {
public static class AppLifecycleObserver implements DefaultLifecycleObserver {
@Override
public void onResume(LifecycleOwner owner) {
// Capture "launch" event when app is "launched"
}
@Override
public void onPause(LifecycleOwner owner) {
// Capture "quit" event when app is "quit"
}
}
private static final AppLifecycleObserver appLifecycleObserver = new AppLifecycleObserver();
private static WeNoteApplication me;
private SharedPreferences sharedPreferences;
@Override
public void onCreate() {
super.onCreate();
me = this;
initLifecycleObserver();
}
private void initLifecycleObserver() {
Lifecycle lifecycle = ProcessLifecycleOwner.get().getLifecycle();
lifecycle.removeObserver(appLifecycleObserver);
lifecycle.addObserver(appLifecycleObserver);
}
public static WeNoteApplication instance() {
return me;
}
}
此方法在大多数情况下都有效,但始终都是如此。
以下是导致应用“退出”事件失败的极端情况。
Intent i = new Intent(context, NoteListAppWidgetConfigureFragmentActivity.class);
// Avoid crash in Android 6.
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
i.putExtra(NoteListAppWidgetConfigureFragmentActivity.INTENT_EXTRA_NOTE_LIST_CONFIG, noteListConfig);
context.startActivity(i);
DefaultLifecycleObserver
的{{1}}没有被调用。androidx.lifecycle.DefaultLifecycleObserver是否有可靠的方法来检测应用退出事件?
答案 0 :(得分:0)
这是因为在我们的主屏幕小部件配置活动中,我们两次调用import numpy as np
train = np.array([[ 0.70436073, 0.91564351, 0.9931506, 2.26418779]])
train_1 = train.reshape(-1, 1)
label = np.array([['1','1','1','0']])
label_1 = label.reshape(-1,1)
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier()
knn.fit(train_1, label_1)
。这使super.onPause
变得一发不可收拾。
DefaultLifecycleObserver
我们只需删除多余的public class StickyNoteAppWidgetConfigureFragmentActivity extends AppCompatActivity {
@Override
public void onPause() {
super.onPause();
// ...
// ...
// ...
super.onPause();
}
}
即可解决此问题。
super.onPause()