如果用語言描述一個項目顯得蒼白無力的時候,我就是讓他看見,所見即所得 (WYSIWYG)。如所示:
1.項目圖如下:
2.增加Shrotcut的如下:
3.增加Shortcut之後Home Screen*(案頭的)如下:
在案頭增加捷徑之後,當想運行這個程式時候可以直接回到Home(案頭)之後點擊這個捷徑就可以運行這個程式了。
代碼的詳細分析如下:
(1)許可權
如果應用程式有增加shortcut(捷徑的功能),它必須在manifest檔案中增加相應的許可權,即:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
(2)建立shortcut的Activity的action:
增加Shortcut的Activity,action是必須是android.intent.action.CREATE_SHORTCUT,如下,也可以在代碼中設定:
<activity android:name=".CreateShortcutActivity" >
<intent-filter>
<action android:name="android.intent.action.CREATE_SHORTCUT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
(3)建立shortcut的代碼:
public static final String
ACTION_CREATE_SHORTCUT Added in API level 1
Activity Action: Creates a shortcut.
Input: Nothing.
Output: An Intent representing the shortcut. The intent must contain three extras: SHORTCUT_INTENT (value: Intent), SHORTCUT_NAME (value: String), and SHORTCUT_ICON (value: Bitmap) or SHORTCUT_ICON_RESOURCE (value: ShortcutIconResource).
大致意思如下,一個Intent代表一個shortcut。這個intent必須包含三部分參數:捷徑的意圖(值為意圖類型),捷徑的名稱(值為字串類型),捷徑的表徵圖(類型為位元影像)或者捷徑表徵圖資源(值為捷徑表徵圖資源類型)。
// Build the intent for the chosen activity
//Set the intent of the shrorcut
Intent intent = new Intent();
intent.setComponent(new ComponentName(info.activityInfo.applicationInfo.packageName,
info.activityInfo.name));
Intent result = new Intent();
result.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
// Set the name of the shortcut
result.putExtra(Intent.EXTRA_SHORTCUT_NAME, info.loadLabel(mPackageManager));
// Build the icon info for shorcut
Drawable drawable = info.loadIcon(mPackageManager);
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bd = (BitmapDrawable) drawable;
result.putExtra(Intent.EXTRA_SHORTCUT_ICON, bd.getBitmap());
}
// Set the result
setResult(RESULT_OK, result);
(4)建立成功之後,發送廣播:
// Boradcast an intent that tells the home screen to create a new shortcut
result.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
sendBroadcast(result);
開源項目apps-for-android 的如下http://code.google.com/p/apps-for-android/