Close application and launch home screen on Android

后端 未结 21 2245
我在风中等你
我在风中等你 2020-11-22 07:33

I have two different activities. The first launches the second one. In the second activity, I call System.exit(0) in order to force the application to close, bu

21条回答
  •  天命终不由人
    2020-11-22 08:21

    Run the second activity using start activity for result:

    Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
    
    //This line is important
    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    
    startActivityForResult(intent, REQUEST_CODE);
    

    Add this function to the first Activity:

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(rquestCode == REQUEST_CODE)
            if(resultCode == RESULT_CANCELED)
                finish();
    }
    

    And add this to the second Activity:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
    
            Log.i(TAG, "Back key pressed");
            setResult(RESULT_CANCELED);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    

提交回复
热议问题