在程序中把一个软件的快捷方式添加到桌面上,只需要如下三步即可:
- 创建一个添加快捷方式的Intent该Intent的Action属性值应该为com.android.launcher.action.INSTALLSHORTCUT。
- 通过为该Intent加Extra属性来设置快捷方式的标题、图标及快捷方式对应启动的程序。
- 调用sendBroadcast()方法发送广播即可添加快捷方式。
private void createShotCut() {
//创建一个添加快捷方式的Intent
Intent addSC=new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
//快捷键的标题
String title="one";
addSC.putExtra("duplicate", false);
//快捷键的图标
Parcelable icon=Intent.ShortcutIconResource.fromContext(
MainActivity.this, R.mipmap.ic_launcher);
//创建单击快捷键启动本程序的Intent
Intent launcherIntent=new Intent(MainActivity.this, MainActivity.class);
//设置快捷键的标题
addSC.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
//设置快捷键的图标
addSC.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
//设置单击此快捷键启动的程序
addSC.putExtra(Intent.EXTRA_SHORTCUT_INTENT,launcherIntent);
//向系统发送添加快捷键的广播
sendBroadcast(addSC);
Toast.makeText(MainActivity.this, "创建成功", Toast.LENGTH_SHORT).show();
}
当然不要忘记添加权限
<!-- 添加快捷方式 -->
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<!-- 移除快捷方式 -->
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
<!-- 查询快捷方式 -->
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
private void removeShortcut(String name) {
// remove shortcut的方法在小米系统上不管用,在三星上可以移除
Intent intent = new Intent(ACTION_REMOVE_SHORTCUT);
// 名字
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
// 设置关联程序
Intent launcherIntent = new Intent(MainActivity.this,
MainActivity.class).setAction(Intent.ACTION_MAIN);
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent);
// 发送广播
sendBroadcast(intent);
}
private boolean hasInstallShortcut(String name) {
boolean hasInstall = false;
final String AUTHORITY = "com.android.launcher2.settings";
Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/favorites?notify=true");
// 这里总是failed to find provider info
// com.android.launcher2.settings和com.android.launcher.settings都不行
Cursor cursor = this.getContentResolver().query(CONTENT_URI,
new String[] { "title", "iconResource" }, "title=?",
new String[] { name }, null);
if (cursor != null && cursor.getCount() > 0) {
hasInstall = true;
}
return hasInstall;
}
3509

被折叠的 条评论
为什么被折叠?



