为Android程序添加桌面快捷方式需要三个步骤。
1,创建一个添加快捷方式的Intent,该Intent的Action属性值为com.android.launcher.action.INSTALL_SHORTCUT。
Intent addIntent = new Intent("com.android.launcher.action.INSTALL_SHOTRCUT");
2,为一中的Intent添加Extra属性来设置快捷方式的标题,图标以及对应的启动程序。
//设置快捷方式图标,通常是程序图标
Parcelable icon = Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.ic_launcher);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,icon);
//设置快捷方式标题,通常也是程序名称
String titlt = getResource().getString(R.String.title);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_SHORCUT_NAME,title);
//设置快捷方式对应的Intent即要启动的程序
Intent myIntent = new Intent(this,this.class);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,myIntent);
3,调用sendBroadcast方法发送广播即可添加快捷方式。
sendBroadcast(addIntent);
程序添加快捷方式需要权限,因此在AndroidManifest.xml文件中需要添加权限
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>