要不怎么說Android特別開放呢,在Android開發(fā)中,只要發(fā)送一個(gè)廣播,就可以實(shí)現(xiàn)這種需求了。
廢話不多說,以下是封裝好的一段代碼。
public class ShortcutUtil {
public static void createShortCut(Activity act, int iconResId,
int appnameResId) {
// com.android.launcher.permission.INSTALL_SHORTCUT
Intent shortcutintent = new Intent(
"com.android.launcher.action.INSTALL_SHORTCUT");
// 不允許重復(fù)創(chuàng)建
shortcutintent.putExtra("duplicate", false);
// 需要現(xiàn)實(shí)的名稱
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
act.getString(appnameResId));
// 快捷圖片
Parcelable icon = Intent.ShortcutIconResource.fromContext(
act.getApplicationContext(), iconResId);
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
// 點(diǎn)擊快捷圖片,運(yùn)行的程序主入口
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
new Intent(act.getApplicationContext(), act.getClass()));
// 發(fā)送廣播
act.sendBroadcast(shortcutintent);
}
}
代碼比較簡單,不做更詳細(xì)的解釋。別忘記增加以下權(quán)限,否則看不到任何效果。
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
另外,這樣做可能并不友好。更好的做法是,第一次運(yùn)行程序的時(shí)候,提示用戶是否創(chuàng)建桌面快捷方式,讓用戶選擇。以后再次運(yùn)行就不再進(jìn)行提示了。