找不到病根真是让人愁白了头;

今天写了一个startActivityForResult,开启一个Activity并拿到返回的结果,但是startActivityForResult刚走,onActivityResult就立即响应了,这我要这个onActivityResult有何用;

来看开启代码:

                        Intent intaentPermission = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
intaentPermission.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intaentPermission.setData(Uri.parse( "package:"+getPackageName()));
startActivityForResult(intaentPermission,windowHintStartPermission);

这个是回调代码:

   @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == windowHintStartPermission){
if (Build.VERSION.SDK_INT >= 23) {
if (!Settings.canDrawOverlays(getActivity())) {
UIHelper.showToast("您未开启悬浮窗权限,遥控正在后台执行");
}else {
Intent intent = new Intent(getActivity(), TelecontrolQueryService.class);
intent.putExtra("id", "");
getActivity().startService(intent);
} }else {
Intent intent = new Intent(getActivity(), TelecontrolQueryService.class);
intent.putExtra("id","");
getActivity().startService(intent);
}
}
}

我真是日了狗了,开启代码刚执行结束,回调代码就走了;

来、划重点了:

经排查,发现这个提前回调跟Activity的启动模式有关(launchMode),举个栗子:Activity1使用startActivityForResult开启Activity2,Activity2的launchMode如果不是标准模式,就会出现提前回调的问题,onActivityResult立即执行;

我的解决方法:

                        Intent intaentPermission = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
// intaentPermission.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //把启动模式注释掉
intaentPermission.setData(Uri.parse( "package:"+getPackageName()));
startActivityForResult(intaentPermission,windowHintStartPermission);

还有就是,不要getActivity().startActivityForResult();在Fragment中开启Activity前面不要加getActivity(). ;不然你的onActivityResult方法会不执行;

04-14 11:19