Add permission:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/><uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT"/>
Code:
private void setUpShortCut() { Intent intent = new Intent(CREATE_SHORTCUT_ACTION); // 設定捷徑圖片 intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(this, R.drawable.logo)); // 設定捷徑名稱 intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "sina"); // 設定是否允許重複建立捷徑 false表示不允許 intent.putExtra("duplicate", false); // 設定捷徑要開啟的intent // 第一種方法建立捷徑要開啟的目標intent Intent targetIntent = new Intent(); // 設定應用程式卸載時同時也刪除案頭捷徑 targetIntent.setAction(Intent.ACTION_MAIN); targetIntent.addCategory("android.intent.category.LAUNCHER"); ComponentName componentName = new ComponentName(getPackageName(), this.getClass().getName()); targetIntent.setComponent(componentName); // 第二種方法建立捷徑要開啟的目標intent intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, targetIntent); // 發送廣播 sendBroadcast(intent);} private void tearDownShortCut() { Intent intent = new Intent(DROP_SHORTCUT_ACTION); // 指定要刪除的shortcut名稱 intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "sina"); String appClass = getPackageName() + "." + this.getLocalClassName(); ComponentName component = new ComponentName(getPackageName(), appClass); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,new Intent().setAction(Intent.ACTION_MAIN).setComponent(component)); sendBroadcast(intent);}
Or:
if (Intent.ACTION_CREATE_SHORTCUT.equals(action)){ setupShortcut(); finish(); return;} ...private void setupShortcut() { // First, set up the shortcut intent. //For this example, we simply create an intent that // will bring us directly back to this activity. //A more typical implementation would use a // data Uri in order to display a more specific result, //or a custom action in order to // launch a specific operation. Intent shortcutIntent = new Intent(Intent.ACTION_MAIN); shortcutIntent.setClassName(this, this.getClass().getName()); shortcutIntent.putExtra(EXTRA_KEY, "ApiDemos Provided This Shortcut"); // Then, set up the container intent (the response to the caller) Intent intent = new Intent(); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.shortcut_name)); Parcelable iconResource = Intent.ShortcutIconResource.fromContext( this, R.drawable.app_sample_code); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); // Now, return the result to the launcher setResult(RESULT_OK, intent);}