Restart Activity with onResume method

前端 未结 2 1691
忘掉有多难
忘掉有多难 2021-01-02 19:03

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
prot         


        
相关标签:
2条回答
  • 2021-01-02 19:14

    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.

    0 讨论(0)
  • 2021-01-02 19:29

    Just use this in your onResume()

    @Override protected void onResume() { recreate(); }

    0 讨论(0)
提交回复
热议问题