我們首先來看Android中為APP創建快捷方式的原理:
從圖上可以看出,Android大致分7步完成快捷方式的創建:
第一步:Android系統的launcher程序會調用它的pickShortcut()方法去啟動系統的pickActivity程序(應用);
第二步:pickActivity程序(應用)啟動后會調用它的CheckIntentFilter()方法,去在系統中尋找可以創建快捷方式的應用有哪些,並且列舉出來。只要第三方 App用<Intent-filter>標簽進行了相應的注冊(具體如何注冊請看下面的代碼)就可以被發現並列舉出來;
第三步:調用Choseitem()方法選擇創建誰的快捷方式;
第四步:完成第三步之后,pickActivity程序(應用)會將選擇的消息通過Intent返回給系統的launcher;
第五步:launcher程序獲得pickActivity返回的消息后,就會知道創建誰的快捷方式,通過調用ProcessShortcut()方法去啟動第三方App中負責創建快捷方式 的Activity,這個Activity就是第二步中我們提到的用<Intent-filter>標簽進行了注冊的Activity;
第六步:第三方App中負責創建快捷方式的Activity會將快捷方式的名稱,圖標和點擊后跳轉路徑通過Intent返回給launcher;
第七部:launcher收到返回的消息后調用本身的ComPleteAddShortcut()方法完成快捷方式的創建,並顯示在桌面上;
分析完原理后,那么作為第三方開發者應該完成哪幾步呢?
我們只需完成如下2步就ok了,其他的事情系統會為我們去做:
首先:用<Intent-filter>標簽進行注冊
<activity android:name=".CreatShortCut"> <intent-filter> <action android:name="android.intent.action.CREATE_SHORTCUT"/> </intent-filter> </activity>
其中的“CreatShortCut”是負責創建快捷方式的Activity的名字。
然后:向Launcher返回相關數據
public class CreatShortCut extends Activity { /** * Description * * @param savedInstanceState * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); if (getIntent().getAction().equals(Intent.ACTION_CREATE_SHORTCUT)) { Intent _returnIntent = new Intent(); _returnIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "csx");// 快捷鍵的名字 _returnIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,// 快捷鍵的ico Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher)); _returnIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(this, MainActivity.class));// 快捷鍵的跳轉Intent setResult(RESULT_OK, _returnIntent);// 發送 finish();// 關閉本Activity } } }
大功告成!!!(網上也有一些其他方法但是都很復雜,不好使用)