在我们安装应用程序的时候,喜欢把常用的软件在桌面上有个快捷方式,那么我们可以在自己的程序中帮用户实现这一点,在用户第一次运行的时候,创建一个快捷方式在桌面上。这里,你也可以给用户个选择,是否需要创建快捷方式。
以下是创建快捷方式的代码:
/**
* 创建桌面快捷方式
*/
private void addShortcut() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
String cls = new StringBuilder(String.valueOf(getPackageName()))
.append(".").append(getLocalClassName()).toString();
ComponentName componentName = new ComponentName(getPackageName(), cls);
intent.setComponent(componentName);
Intent shortCut = new Intent();
shortCut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
// 快捷方式的名称
shortCut.putExtra(Intent.EXTRA_SHORTCUT_NAME,
getString(R.string.app_name));
// 快捷方式的ICON
Intent.ShortcutIconResource iconResource = Intent.ShortcutIconResource
.fromContext(this, R.drawable.icon);
shortCut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
// 不允许重复创建
shortCut.putExtra("duplicate", false);
shortCut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
sendBroadcast(shortCut);
}
最后,注意增加权限:<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
删除:
/**
* 删除程序的快捷方式
*/
private void delShortcut(){
Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
//快捷方式的名称
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
//指定当前的Activity为快捷方式启动的对象: 如 com.everest.video.VideoPlayer
//注意: ComponentName的第二个参数必须是完整的类名(包名+类名),否则无法删除快捷方式
String appClass = this.getPackageName() + "." +this.getLocalClassName();
ComponentName comp = new ComponentName(this.getPackageName(), appClass);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));
sendBroadcast(shortcut);
}
声明权限
在AndroidManifest.xml 文件中声明 创建和删除快捷方式时声明权限
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />