[Android]为指定的应用创建桌面快捷方式
生活随笔
收集整理的這篇文章主要介紹了
[Android]为指定的应用创建桌面快捷方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
??? 網上一搜一大把為自己的應用創建快捷方式,但是本文的側重點在為“指定的應用”創建桌面快捷方式。
?? ?常見的桌面快捷方式有兩要素: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;
}
?
?
轉載于:https://www.cnblogs.com/error404/archive/2011/12/23/2299333.html
總結
以上是生活随笔為你收集整理的[Android]为指定的应用创建桌面快捷方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux权限补充:rwt rwT rw
- 下一篇: 我是奇克