您的位置:首页 > 移动开发 > Android开发

为android应用程序添加桌面快捷方式

2012-10-17 21:36 661 查看

概览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相同。否则,会出现意想不到的异常。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: