How to exit from the application and show the home screen?

后端 未结 20 2284
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 09:45

I have an application where on the home page I have buttons for navigation through the application.

On that page I have a button \"EXIT\" which when clicked should t

20条回答
  •  野性不改
    2020-11-22 10:13

    (I tried previous answers but they lacks in some points. For example if you don't do a return; after finishing activity, remaining activity code runs. Also you need to edit onCreate with return. If you doesn't run super.onCreate() you will get a runtime error)

    Say you have MainActivity and ChildActivity.

    Inside ChildActivity add this:

    Intent intent = new Intent(ChildActivity.this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("EXIT", true);
    startActivity(intent);
    return true;
    

    Inside MainActivity's onCreate add this:

    @Override
    public void onCreate(Bundle savedInstanceState) {
    
        mContext = getApplicationContext();
    
        super.onCreate(savedInstanceState);
    
        if (getIntent().getBooleanExtra("EXIT", false)) {
            finish();
            return;
        }
        // your current codes
        // your current codes
    }
    

提交回复
热议问题