setResult does not work when BACK button pressed

I am trying to setResult after the BACK button was pressed. I call in onDestroy

Intent data = new Intent();
setResult(RESULT_OK, data) 

But when it comes to

onActivityResult(int requestCode, int resultCode, Intent data) 

the resultCode is 0 (RESULT_CANCELED) and data is 'null'.

So, how can I pass result from activity terminated by BACK button?


您需要覆盖onBackPressed()方法并在调用超类之前设置结果,即

@Override
public void onBackPressed() {
    Bundle bundle = new Bundle();
    bundle.putString(FIELD_A, mA.getText().toString());

    Intent mIntent = new Intent();
    mIntent.putExtras(bundle);
    setResult(RESULT_OK, mIntent);
    super.onBackPressed();
}

Activity result must be set before finish() is called. Clicking BACK actually calls finish() on your activity , so you can use the following snippet:

@Override
public void finish() {
    Intent data = new Intent();
    setResult(RESULT_OK, data); 

    super.finish();
}

If you call NavUtils.navigateUpFromSameTask(); in onOptionsItemSelected() , finish() is called, but you will get the wrong result code . So you have to call finish() not navigateUpFromSameTask in onOptionsItemSelected() . wrong requestCode in onActivityResult


如果你想在onBackPressed事件中设置一些自定义的RESULT_CODE ,那么你需要先设置result ,然后调用super.onBackPressed()并且你将在调用者活动的onActivityResult方法中收到相同的RESULT_CODE

    @Override
    public void onBackPressed()
    {
         setResult(SOME_INTEGER);
         super.onBackPressed();
    }
链接地址: http://www.djcxy.com/p/31896.html

上一篇: 如何处理活动中的后退按钮

下一篇: 按BACK按钮时,setResult不起作用