Android应用开发之(如何自动在桌面创建快捷方式)
一般来说在 Android 中添加快捷方式的有以下两种:
?
</intent-filter>
复制代码创建核心代码:
if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
?
Intent shortcut = new Intent(Intent.ACTION_CREATE_SHORTCUT);
?????// 不允许重建
?????shortcut.putExtra("duplicate", false);
?????// 设置名字
?????shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,
?????????????this.getString(R.string.app_name));
?????// 设置图标
?????shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
?????????????Intent.ShortcutIconResource.fromContext(this,
?????????????????????R.drawable.ic_launcher));
?????// 设置意图和快捷方式关联的程序
?????shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
?????????????new Intent(this, this.getClass())); ????
????????//将结果返回到launcher
????????setResult(RESULT_OK, intent); ??????
????}
在launcher中我们运行程序就可以将快捷方式创建在桌面上。
???????????????????????????????????????
通过上述方式可以自动将快捷方式创建到桌面上,但是每次运行程序时都会将快捷方式创建到桌面上,下面我们将通过程序判断快捷方式是否已经创建到桌面上了,基本思路是:由于快捷方式launcher管理的,我们可以通过查看launcher中是否已经有此快捷方式数据,如果有就不在创建。
主要代码如下:
/**
??* 添加权限:<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"/>
??* ?
??* @return
??*/
?private boolean hasInstallShortcut() {
?????boolean hasInstall = false;
?????final String AUTHORITY = "com.android.launcher.settings";
?????Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
?????????????+ "/favorites?notify=true");
?????Cursor cursor = this.getContentResolver().query(CONTENT_URI,
?????????????new String[] { "title", "iconResource" }, "title=?",
?????????????new String[] { this.getString(R.string.app_name) }, null);
?????if (cursor != null && cursor.getCount() > 0) {
?????????hasInstall = true;
?????}
?????return hasInstall;
?}
?
上述查询操作,需要具有以下权限:
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"></uses-permission>
注意通过程序创建的快捷方式不会随着程序卸载而自动删除。
?
原文地址:http://xmagicj.diandian.com/post/2012-04-01/17357119