Android 使用onResume方法重新启动活动
我想用onResume()方法重新启动活动。我想我可以用一个意图来实现这一点,但这最终是一个无休止的循环Android 使用onResume方法重新启动活动,android,android-activity,Android,Android Activity,我想用onResume()方法重新启动活动。我想我可以用一个意图来实现这一点,但这最终是一个无休止的循环 @Override protected void onResume() { Intent intent = new Intent(MainActivity.this, MainActivity.class); MainActivity.this.startActivity(intent); finish(); super.onResume(); } 是否有其
@Override
protected void onResume() {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
MainActivity.this.startActivity(intent);
finish();
super.onResume();
}
是否有其他方法可以重新启动活动?我想问您为什么要这样做。。。但我想到的第一件事是:
@Override
protected void onCreate(Bundle savedInstanceState) {
...
Log.v("Example", "onCreate");
getIntent().setAction("Already created");
}
@Override
protected void onResume() {
Log.v("Example", "onResume");
String action = getIntent().getAction();
// Prevent endless loop by adding a unique action, don't restart if action is present
if(action == null || !action.equals("Already created")) {
Log.v("Example", "Force restart");
Intent intent = new Intent(this, Example.class);
startActivity(intent);
finish();
}
// Remove the unique action so the next time onResume is called it will restart
else
getIntent().setAction(null);
super.onResume();
}
您应该使
“已创建”
唯一,这样就不会有其他意图意外地执行此操作。只需在您的onResume()中使用此操作即可
@覆盖
受保护的void onResume(){
重新创建();
}
是的……当活动重新启动时,将再次调用onResume。。。然后活动将重新启动。。。然后将再次调用onResume。不确定该用户正在尝试什么,但它无法工作。@user1627867我更新了我的答案。第一个版本导致应用程序重新启动两次,此新版本按预期工作。其处于循环中。oops 2019-10-30 13:07:19.304 26192-26192/com.example.android.appusagentastics I/lifeCycle:在oncreate中,您编写的代码是一个递归循环是的。OnResume也会触发新的意图。你真正想要实现的是什么。