参考源码,知道创建快捷方式是通过发广播给receiver实现的。
第一步:
指定Action为:
com.android.launcher.action.INSTALL_SHORTCUT
第二步:
指定名称:
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "手机管家");
第三步:
指定图标:
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON,
BitmapFactory.decodeResource(getResources(), R.drawable.icon));
第四步:
指定要干什么事情:
Intent shortcutIntent = new Intent();
shortcutIntent.setAction(Intent.ACTION_MAIN);
shortcutIntent.addCategory(Intent.CATEGORY_DEFAULT);
shortcutIntent.setClassName(getPackageName(),
"com.ustc.mobilemanager.SplashActivity");
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
第五步:
发送广播:
sendBroadcast(intent);
运行,发现程序并没有创建快捷方式,查看logcat日志,发现了一点:需要添加权限:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
现在运行,OK了,不过我们的程序每次进入都会创建一个快捷方式,这个太。。。所以我们需要知道当我们创建过了之后就不要再创建了:
完整的代码如下:
/**
* 创建快捷方式
*
*/
private void installShortcut() {
boolean shortcut = sp.getBoolean("shortcut", false);
if (shortcut) {
return;
}
Editor editor = sp.edit();
// 发送广播的Intent
Intent intent = new Intent();
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
// 快捷方式,要包含三个重要的信息:1.名称;2.图标;3.干什么事情
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "手机管家");
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON,
BitmapFactory.decodeResource(getResources(), R.drawable.icon));
Intent shortcutIntent = new Intent();
shortcutIntent.setAction(Intent.ACTION_MAIN);
shortcutIntent.addCategory(Intent.CATEGORY_DEFAULT);
shortcutIntent.setClassName(getPackageName(),
"com.ustc.mobilemanager.SplashActivity");
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
sendBroadcast(intent);
Toast.makeText(this, "已创建手机管家快捷方式", 0).show();
editor.putBoolean("shortcut", true);
editor.commit();
}
在onCreate()方法中调用。