这个问题可能是由Android系统杀死了应用程序进程造成的。为了保持应用程序的持久性,可以在Application类中实现以下代码来重新启动应用程序:
public class MyApplication extends Application {
private static MyApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@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 outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
public static MyApplication getInstance() {
return instance;
}
}
这里的MyApplication
类是应用程序的自定义Application
类。我们实现了ActivityLifecycleCallbacks
接口中的onActivityDestroyed
方法,并在该方法中启动了MainActivity
。这样就可以实现自动重启应用程序。