简体   繁体   English

尝试从本身无法重新加载Android活动

[英]Trying to reload an Android activity from itself not working

My problem is: I can't figure out a way to restart my activity from itself. 我的问题是:我找不到从自己重新开始活动的方法。 For example in a game, if you die, there's a menu with an option to retry, which restart the stage instantly. 例如,在游戏中,如果您死了,则存在一个带有重试选项的菜单,该菜单可立即重新启动舞台。 That's exactly the case. 确实是这样。

As i have read from a lot of others answers on this matter, there are 2 main methods for reloading an activity: 正如我从其他许多人那里得到的关于此问题的答案中所读到的,有2种主要方法可以重新加载活动:

1- finish(); startActivity(getIntent()); 1- finish(); startActivity(getIntent()); finish(); startActivity(getIntent());

2- recreate(); 2- recreate();

The first method doesn't seem to work for me because it restart the activity, but leave the previous created one open on the back of my stack. 第一种方法似乎对我不起作用,因为它重新启动了活动,但是将先前创建的方法留在了堆栈的背面。 Looks like the finish() statement is not doing its stuff. 看起来finish()语句没有做任何事情。 I have tried to put it in front, after, and all kind of ways, but it never closes the activity left behind. 我尝试过将它放在前面,后面和各种各样的方式中,但是它永远不会关闭剩下的活动。

On the other hand, the option number 2 cannot be called (as far as i know) from outside the UI thread, and if i do, the app crashes. 另一方面,选项编号2不能从UI线程外部调用(据我所知),如果我这样做,则应用程序崩溃。 I tried to call the recreate method using: 我试图使用以下方法调用recreate方法:

    Activity.this.runOnUiThread(new Runnable() {
        public void run() {
            recreate();
        }
    });

But this approach gives me a very awful blinking on my screen. 但是这种方法使我的屏幕闪烁得非常糟糕。 A black screen suddenly appears, and that doesn't seems right. 黑屏突然出现,这似乎不正确。

Try this: 尝试这个:

    Intent intent = getActivity().getIntent();
    getActivity().finish();
    startActivity(intent);

You should add FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK 您应该添加FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK flags to the intent, such as: 该意图的FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK标志,例如:

Intent intent = getActivity().getIntent();
intent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK);
getActivity().finish();
startActivity(intent);

This will force the system to remove the previous task from the stack. 这将迫使系统从堆栈中删除先前的任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM