原生的Android系统装的Android应用默认不会显示在桌面快捷方式上,好多程序为了增强粘性而让程序自动生成快捷方式。而生成的方式就是给桌面发送广播。
(1)创建删除快捷方式需要权限:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT"/>
(2)工具类ShortcutUtils.java
public class ShortcutUtils {
/**
* 创建快捷方式
* @param context
* @param shortcutName 快捷方式名称
* @param iconRes 快捷方式图标 R.mipmap/R.drawable
* @param actionIntent 快捷方式动作
* @param allowRepeat 是否允许重复创建
*/
public static void addShortcut(Context context, String shortcutName, int iconRes,
Intent actionIntent,boolean allowRepeat){
Intent shortcutintent = new Intent("com.android.launch.action.INSTALL_SHORTCUT");
shortcutintent.putExtra("duplicate",allowRepeat);
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME,shortcutName);
Parcelable icon = Intent.ShortcutIconResource.fromContext(context.getApplicationContext(),iconRes);
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,icon);
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,actionIntent);
context.sendBroadcast(shortcutintent);
}
/**
* 创建快捷方式
* @param context
* @param shortcutName 快捷方式名称
* @param bitmap 快捷方式图标 ,设置图片方式和上面的方法不同
* @param actionIntent 快捷方式动作
* @param allowRepeat 是否允许重复创建
*/
public static void addShortcut(Context context, String shortcutName, Bitmap bitmap,
Intent actionIntent,boolean allowRepeat){
Intent shortcutintent = new Intent("com.android.launch.action.INSTALL_SHORTCUT");
shortcutintent.putExtra("duplicate",allowRepeat);
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME,shortcutName);
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,bitmap);
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,actionIntent);
context.sendBroadcast(shortcutintent);
}
/**
* 删除快捷方式
* @param context
* @param name
* @param actionIntent
* @param allowRepeat
*/
public void deleteShortcut(Context context,String name,Intent actionIntent,
boolean allowRepeat){
Intent shortcutintent = new Intent("com.android.launch.action.INSTALL_SHORTCUT");
shortcutintent.putExtra("duplicate",allowRepeat);
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME,name);
shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,actionIntent);
context.sendBroadcast(shortcutintent);
}
}
(3) 调用代码
public void addShortCut(){
Log.i("addShortCut","addShortCut is running ");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.baidu.com"));
intent.addCategory(Intent.CATEGORY_LAUNCHER); //防止重复启动App
ShortcutUtils.addShortcut(this,"打开百度",R.
drawable.baidu,intent,false);
}
以上是《爱上Android》这本书中的示例,大家有补充的希望提醒,谢谢!