Activity设置singleInstance后不能启用startActivityForResult()进行数据回调

   一般情况下如果我们想从A跳到B,并希望B操作完毕后返回操作结果到A,我们第一时间就会想到运用startActivityForResult()进行处理 

    但是...

    如果A的LauncherMode设置成了singleTop或者singleInstance,这招就会失灵

查看startActivityForResult()的文档,是这样描述的:

                   Note that this method should only be used with Intent protocols that are defined to return a result. In other protocols (such asandroid.content.Intent.ACTION_MAIN or android.content.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.


最后一句大概意思是如果你将A设置成了singleTask那么你启动B时不会等待返回,只会马上得到返回码为Activity.RESULT_CANCELED.是不会得到你想要的结果的。


    其实这个时候需要使用方法onNowIntent(Intent intent)主动获取,而不是等待startActivityForResult()的返回

详细如下:

    1, 在A启动B时,使用平常的startActivity()方法

    2,在B处理完毕准备返回结果时,直接通过startActivity()重新激活栈中的A,这时应该将你想返回的数据寄存到intent里面

[html]  view plain copy
  1. Intent intent = new Intent(this, A.class);  
  2. intent.putExtra("your callback data label", "your callback data");  
  3. startActivity(intent);  
    3,在A中的onNowIntent()实现获取返回参数的方法

[html]  view plain copy
  1. @Override  
  2. protected void onNewIntent(Intent intent) { // ActManager设置了singleInstance,可以通过这个方法获取重新启动ActManager的intent数据  
  3.     // TODO Auto-generated method stub  
  4.     super.onNewIntent(intent);  
  5.     backDetail = intent.getBooleanExtra("delete", true);  
  6. }  
    4,在A中实现onResume()方法,通过这个生命周期的这一步,实现自动处理返回数据的效果

[html]  view plain copy
  1. public void onResume() {  
  2.     super.onResume();  
  3.     if (backDetail) {  
  4.         // do somthing  
  5.     }  
  6. }  

    就这样可以实现singleInstance的参数回调
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值