監聽home鍵(android:launchMode=”singleTask” 與 onNewIntent(Intent intent) 的用法)

來源:互聯網
上載者:User

android:launchMode="singleTask" 和 onNewIntent(Intent intent)兩個特性,現總結一下經驗:

android:launchMode="singleTask" 配置在 Mainifest 中,它保證了棧中此Activity總是只有一個,無論你啟動它多少次;

onNewIntent(Intent intent) 是Override Activity的父類方法,只有僅在點Home鍵退出Activity而再次啟動新的Intent進來才被調用到;

它們兩結合使用,可以做到監聽home鍵(僅當發起新的Intent)。

代碼如下:

Manifest.xml

<activity android:name=".OnNewIntentDemo" android:launchMode="singleTask" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="video/*" /> </intent-filter></activity>

Activity 中

@Override protected void onNewIntent(Intent intent) { if(DEBUG) Log.i(TAG, "onNewIntent ~~~~~~~ intent = "+intent); super.onNewIntent(intent); }

注意: 當按Home鍵退出,再長按Home鍵進入,此時onNewIntent不被訪問,因為再次進入的時候沒有被發起Intent 。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.