Android startActivityForResult与singleTask使用问题

           我们都知道在activity中有一个方法startActivityForResult,(假设有两个activity A,B)该方法的作用就是在activity A启动一个activity B后,如果该activity B调用finish方法,会触发activity B的onActivityForResult方法,在该方法中我们可以获取activity B需要返回给Activity A的数据,然而当启动的activity A的启动模式为singleTash或者singleInstance时,在调用startActivityForResult方法时会立即回调onActivityForResult方法,并且其中的resultCode为cancel值,这是什么原因呢?我们查看系统源码:

/**
 * Launch an activity for which you would like a result when it finished.
 * When this activity exits, your
 * onActivityResult() method will be called with the given requestCode. 
 * Using a negative requestCode is the same as calling 
 * {@link #startActivity} (the activity is not launched as a sub-activity).
 * 
 * 

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. * *

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. * *

This method throws {@link android.content.ActivityNotFoundException} * if there was no Activity found to run the given Intent. * * @param intent The intent to start. * @param requestCode If >= 0, this code will be returned in * onActivityResult() when the activity exits. * * @throws android.content.ActivityNotFoundException * * @see #startActivity */ public void startActivityForResult(Intent intent, int requestCode)

       上面注释已经写的很清楚了,当启动的activity B是singleTask时, activity A和activity B两个activity不在同一个任务栈中(这个地方有歧义,实际上以singleTask启动模式启动一个activity并不一定会重新开启一个任务栈,只有当系统中不存在与该activity的TaskAffinity相同的任务栈时,系统才会创建一个新的任务栈),所以activity A将会立即得到一个cancel的结果。

     所以为了满足任务栈中只存在一个activity B,同时又能够正常使用activity的startActivityForResult,我们可以将activity的启动模式设置为standard同时将intent添加一个flag:Intent.FLAG_CTIVITY_CLEAR_TOP.


你可能感兴趣的:(android,java)