Answers:
您需要在调用超类之前覆盖该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必须在 finish()调用之前设置结果。单击后退实际上是调用finish()你的activity,所以你可以使用下面的代码片段:
@Override
public void finish() {
Intent data = new Intent();
setResult(RESULT_OK, data);
super.finish();
}
如果你打电话NavUtils.navigateUpFromSameTask();的onOptionsItemSelected(),finish()是所谓的,但你会得到错误的result code。因此,您必须finish()不navigateUpFromSameTask打入onOptionsItemSelected()。
onActivityResult中的requestCode错误
finish与onPause和有什么关系onDestroy?这些是完全没有关系的除外finish开始终止的过程,onPause并且onDestroy是一部分。
如果您想RESULT_CODE在onBackPressed事件中设置一些自定义,则需要先设置result,然后调用,super.onBackPressed()然后您将RESULT_CODE在调用者活动的onActivityResult方法中收到相同的信息
@Override
public void onBackPressed()
{
setResult(SOME_INTEGER);
super.onBackPressed();
}
您应该像这样覆盖onOptionsItemSelected:
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
final Intent mIntent = new Intent();
mIntent.putExtra("param", "value");
setResult(RESULT_OK, mIntent);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
请参阅onActivityResult(int,int,Intent)文档
解决方案是检查resultCode的值Activity.RESULT_CENCELED。如果是,则表示按下了BACK或活动崩溃。希望它对你们有用,对我有用:)。
onDestroy在链中为时已晚-请覆盖onPause并检查isFinishing()您的活动是否处于生命周期的尽头。
尝试覆盖onBackPressed(从android 5向上版本),或覆盖onKeyDown()并捕获KeyEvent.BUTTON_BACK(请参阅Android Activity Results)。
当您返回初始活动时,不要依赖在一个活动的onPause中执行的任何逻辑。根据文档:
此方法的实现(onPause)必须非常快,因为在此方法返回之前,下一个活动将不会恢复
参见http://goo.gl/8S2Y详情,。
最安全的方法是在每次结果更改操作完成后设置结果(如您在回答中所述)
我粘贴答案可能对其他人会有所帮助:当设置了带有android:launchMode =“ singleTask”的launcheMode时,我也无法获得结果,医生说:
/* <p>Note that this method should only be used with Intent protocols
* that are defined to return a result. In other protocols (such as
* {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
* not get the result when you expect. For example, if the activity you
* are launching uses the singleTask launch mode, it will not run in your
* task and thus you will immediately receive a cancel result.
*/
和:
/* <p>As a special case, if you call startActivityForResult() with a requestCode
* >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
* activity, then your window will not be displayed until a result is
* returned back from the started activity. This is to avoid visible
* flickering when redirecting to another activity.
*/