標籤:
Android建立案頭的捷徑
概述 :建立案頭捷徑相當與建立一個程式的入口,就像我們程式在安裝完畢後會自動建立一個表徵圖到案頭。其實建立案頭捷徑跟建立一個程式入口差不多,但是像QQ會話一樣建立一個QQ好友的會話捷徑,就得動態建立表徵圖,名字了。
1.首先許可權是必不可少的
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
2.然後就是在你項目設定檔裡面配置
<activity android:name="com.easemob.chatuidemo.activity.ChatActivity" > <intent-filter> <category android:name="android.intent.category.LAUNCHER" /> <action android:name="android.intent.action.CREATE_SHORTCUT" /> </intent-filter></activity>
這個actvity即為你要捷徑點擊後跳轉的那一個activity
3.然後就是你要建立捷徑的方法。
代碼如下:
public void CreateShotCut(final Context context, final Class<?> clazz, final String name, final String image) { Intent shortcutIntent = new Intent(Intent.ACTION_MAIN); // 加入action,和category之後,程式卸載的時候才會主動將該捷徑也卸載 shortcutIntent.addCategory(Intent.CATEGORY_LAUNCHER); shortcutIntent.setClass(context, clazz); /** * 建立一個Bundle對象讓其儲存將要傳遞的值 */ Bundle bundle = new Bundle(); bundle.putString("userId", userId); shortcutIntent.putExtras(bundle); /** * 設定這條屬性,可以使點擊捷徑後關閉其他的任務棧的其他activity,然後建立指定的acticity */ shortcutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 建立捷徑的Intent Intent shortcut = new Intent(Intent.ACTION_CREATE_SHORTCUT); // 不允許重複建立 shortcut.putExtra("duplicate", false); // 點擊快捷圖片,啟動並執行程式主入口 shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); // 需要現實的名稱 shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); // 快捷圖片 Parcelable icon = Intent.ShortcutIconResource.fromContext( getApplicationContext(), R.drawable.ic_launcher); shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon); shortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); context.sendBroadcast(shortcut);}
這行代碼的重要性就在如果沒有這一行,那麼在你點擊這個捷徑,跳轉的時候就會直接跳到這個應用的棧頂(如果指定的activity在棧頂,也不會跳轉其上而是銷毀)而不是指定的那一個Activity(剛開始沒加這條屬性的時候,一直跳轉不到指定的activity上)。 shortcutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
如果想要動態添加圖片即建立捷徑的時候擷取網路上的圖片來進行設定其快捷圖片則使用
// Intent.EXTRA_SHORTCUT_ICON 是bitmap對象shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON,bitmap);
這行代碼,你可以請求網路圖片後轉換為BitMap後設定進去。
ok動態建立捷徑就這樣完成了。
Android案頭捷徑