1. onActivityResult是比onResume先调用的,而且如果onActivityResult中的code比较耗时的话,会阻塞onResume,可以通过如下的code进行测试:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.w(TAG, "on activity result start to deal with: " + requestCode);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.w(TAG, "on activity result end");
}
public void onResume() {
super.onResume();
Log.w(TAG, "on resume start");
}
打印的次序应该是
MainActivity: on activity result start to deal with: 13
MainActivity: on activity result end
MainActivity: on resume start
refer onActivityResult() & onResume()
2. 在activity和fragment并存的时候startActivityForResult
如果在host activity中重写了onActivityResult,那么应该调用super.onActivityResult,这样才能保证fragment中的onActivityResult会被调用
通过如下片段测试:
host activity中有一个fragment,fragment通过两种方式startActivityForResult
1)
Intent intent = new Intent(getContext(), SecondActivity.class);
startActivityForResult(intent, 12);
2)
Intent intent = new Intent(getContext(), SecondActivity.class);
getActivity().startActivityForResult(intent, 13);
注意两者之间的区别,第二个显示调用了getActivity
并且在fragment中设置onActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.w(TAG, "on activity result start to deal with: " + requestCode);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.w(TAG, "on activity result end");
}
public void onResume() {
super.onResume();
Log.w(TAG, "on resume start");
}
在host activity中
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.w(TAG, "on activity result start to deal with: " + requestCode);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.w(TAG, "on activity result end");
}
public void onResume() {
super.onResume();
Log.w(TAG, "on resume start");
}
结果,如果通过方式1 startActivityForResult,会发现fragment中的onActivityResult先被调用,然后到host activity中的onActivityResult,但是host activity中获取的requestCode是一个随机值:
FirstFragment: on activity result start to deal with: 12
FirstFragment: on activity result end
MainActivity: on activity result start to deal with: 196620
MainActivity: on activity result end
MainActivity: on resume start
FirstFragment: on resume start
如果是方式2,fragment中的onActivityResult不会被调用,host activity中获取到的requestCode是准确的:
MainActivity: on activity result start to deal with: 13
MainActivity: on activity result end
MainActivity: on resume start
FirstFragment: on resume start
refer onActivityResult not being called in Fragment
这样的问题也需要在androidannotations中引起注意,
ProcessActivity_.intent(this).startForResult(12)
这边intent中用this,还是getActivity(),onActivityResult的响应是不一样的