概覽Outline
1 目的
2 實現
3 檢測是否已經生成了桌面快捷方式
4 注意事項
1目的
市場上大多數android應用程序在第一次運行時都會給桌面添加所安裝應用程序的快捷方式(shortcut),
比如手機QQ、UC瀏覽器等。這樣給用戶的方便是顯而易見的。如此,你也會想到給自己的應用程序
添加桌面快捷方式了吧。本文的目的是,在用戶安裝你的應用程序時,自動生成應用程序的桌面快捷方式。
2實現
private void addShortcutToDesktop() {
Intent shortcut = new Intent(
"com.android.launcher.action.INSTALL_SHORTCUT");
// 不允許重建
shortcut.putExtra("duplicate", false);
// 設置名字
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,
getString(R.string.app_name));// 桌面快捷方式名稱
// 設置圖標
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(this,
R.drawable.ic_launchermain));
// 設置意圖和快捷方式關聯程序
Intent intent = new Intent(this, this.getClass());
// 桌面圖標和應用綁定,卸載應用後系統會同時自動刪除圖標
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
// 發送廣播
sendBroadcast(shortcut);
}
3檢測是否已經生成了桌面快捷方式
private boolean isShortcutInstalled() {
boolean isInstallShortcut = false;
final ContentResolver cr = mContext.getContentResolver();
// 2.2系統是”com.android.launcher2.settings”,網上見其他的爲"com.android.launcher.settings"
String AUTHORITY = null;
/*
* 根據版本號設置Uri的AUTHORITY
*/
if (getSystemVersion() >= 8) {
AUTHORITY = "com.android.launcher2.settings";
} else {
AUTHORITY = "com.android.launcher.settings";
}
Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/favorites?notify=true");
Cursor c = cr.query(CONTENT_URI,
new String[] { "title", "iconResource" }, "title=?",
new String[] { getString(R.string.app_name) }, null);// 這裏得保證app_name與創建
//快捷方式名的一致,否則會出現提示“快捷方式已經創建”
if (c != null && c.getCount() > 0) {
isInstallShortcut = true;
}
return isInstallShortcut;
}
4注意事項
1 添加權限。可想而知,爲了能夠實現目的,還得有生成快捷方式的權限:
<uses-permissionandroid:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permissionandroid:name="com.android.launcher.permission.UNINSTALL_SHORTCUT"/>
<!—讀取相關設置的權限-->
<uses-permissionandroid:name="com.android.launcher.permission.READ_SETTINGS" />
2 必須保證快捷方式名與app_name相同。在給快捷方式設置名字的時候推薦使用資源讀取app_name的方式,如果想直接用字
符串給出的話,至少保證與app_name相同。否則,會出現意想不到的異常。