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

来源:互联网 发布:一列数据怎么求和 编辑:程序博客网 时间:2024/06/05 18:39

   一般情况下如果我们想从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 plaincopy
  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 plaincopy
  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 plaincopy
  1. public void onResume() {  
  2.     super.onResume();  
  3.     if (backDetail) {  
  4.         // do somthing  
  5.     }  
  6. }  

    就这样可以实现singleInstance的参数回调
原创粉丝点击