重新启动活动与onResume方法重新启动、方法、onResume

2023-09-12 22:19:03 作者:无耻的占有欲

我想重新启动与onResume()方法的activitiy。我想我可以用一个Intent来实现的,但在一个无限循环的结束。

I'd like to restart an activitiy with the onResume() method. I thought i can use an Intent to achieve that, but that ends in an endless loop.

@Override
protected void onResume() {
    Intent intent = new Intent(MainActivity.this, MainActivity.class);
    MainActivity.this.startActivity(intent);
    finish();
    super.onResume();
}

有另一种方式重新开始活动?

Is there another way to restart an activity?

推荐答案

我会问你为什么要这么做......但这里要说的是突然出现在我的脑海里的第一件事就是:

I would question why you want to do this... but here is the first thing that popped into my mind:

@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();
}

您应该已创建唯一的,这样没有其他的意图可能会意外地有这个动作。

You should make "Already created" unique so that no other Intent might accidentally has this action.