Android singleTask或singleInstance與startActivityForResult衝突解決

來源:互聯網
上載者:User

從Activity A中使用startActivityForResult啟動Activity B(Manifest中Activity的聲明包含android:launchMode="singleTask"),但是調用startActivityForResult後馬上調用A裡面的protected void onActivityResult(int requestCode, int resultCode, Intent data),系統返回resultCode=RESULT_CANCELED。在B中的setResult也沒有任何意義了。

Logcat輸出如下的資訊:

Activity is launching as a new task, so cancelling activity result.

看了startActivityForResult的文檔中有下面關鍵一句:

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.


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

也就是說B不能是單例或單任務啟動模式,即launchMode不能這樣設定:

android:launchMode="singleInstance"android:launchMode="singleTask"

去掉B 中的如上設定,運行正常。

因此,對於singInstance或singleTask的Activity只能採用其他的方式來傳遞資料。

這兩個LaunchMode標識只能用在startActivity()的方法中,而不能使用在startActivityForResult方法中。因為從Task的角度看,Android認為不同Task之間的Activity是不能傳遞資料的。所以也不會有有用的result返回。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.