轉載地址:http://blog.csdn.net/sodino/article/details/6624521
網上一搜一大把爲自己的應用創建快捷方式,但是本文的側重點在爲“指定的應用”創建桌面快捷方式。常見的桌面快捷方式有兩要素:1.應用名 2.應用圖標。
指定應用圖標的信息是:
// pkgContext爲指定應用的上下文環境,iconIdentifier爲一個整數,指定應用的圖標標識符
ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(pkgContext,
iconIdentifier);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
創建第三方應用的快捷方式關鍵在於如何獲取第三方應用的上下文環境,關鍵代碼爲:
Context pkgContext = context.createPackageContext(pkg, Context.CONTEXT_IGNORE_SECURITY
| Context.CONTEXT_INCLUDE_CODE);
OK,基礎知識講完了,下面直接給代碼以饗讀者。
/**
* @param context
* 執行者。
* @params pkg 待添加快捷方式的應用包名,其值不可爲null。
* @return 返回true爲正常執行完畢,<br/>
* 返回false爲pkg值爲null或者找不到該應用或者該應用無用於Launch的MainActivity 。
* @author sodino
* */
public boolean addShortcut(Context context, String pkg) {
// 快捷方式名
String title = "unknown";
// MainActivity完整名
String mainAct = null;
// 應用圖標標識
int iconIdentifier = 0;
// 根據包名尋找MainActivity
PackageManager pkgMag = context.getPackageManager();
Intent queryIntent = new Intent(Intent.ACTION_MAIN, null);
queryIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> list = pkgMag.queryIntentActivities(queryIntent,
PackageManager.GET_ACTIVITIES);
for (int i = 0; i < list.size(); i++) {
ResolveInfo info = list.get(i);
if (info.activityInfo.packageName.equals(pkg)) {
title = info.loadLabel(pkgMag).toString();
mainAct = info.activityInfo.name;
iconIdentifier = info.activityInfo.applicationInfo.icon;
break;
}
}
if (mainAct == null) {
// 沒有啓動類
return false;
}
Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
// 快捷方式的名稱
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
//不允許重複創建
// shortcut.putExtra("duplicate", false);
ComponentName comp = new ComponentName(pkg, mainAct);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
new Intent(Intent.ACTION_MAIN).setComponent(comp));
// 快捷方式的圖標
Context pkgContext = null;
if (context.getPackageName().equals(pkg)) {
pkgContext = context;
} else {
// 創建第三方應用的上下文環境,爲的是能夠根據該應用的圖標標識符尋找到圖標文件。
try {
pkgContext = context.createPackageContext(pkg, Context.CONTEXT_IGNORE_SECURITY
| Context.CONTEXT_INCLUDE_CODE);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
if (pkgContext != null) {
ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(pkgContext,
iconIdentifier);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
}
// 發送廣播,讓接收者創建快捷方式
// 需權限<uses-permission
// android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
context.sendBroadcast(shortcut);
return true;
}