重新启动活动与onResume方法 [英] Restart Activity with onResume method

查看:167
本文介绍了重新启动活动与onResume方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重新启动与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.

这篇关于重新启动活动与onResume方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆