[mobilesafe] 07_创建桌面快捷方式细节

Android 4.0

创建桌面快捷方式细节

核心代码 : 
/**
 * 7、创建桌面图标,开启HomeActivity
 */
private void installShortcut() {
    Intent intent = new Intent();
    intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    // 1、指定快捷方式名字
    intent.putExtra(Intent.EXTRA_SHORTCUT_NAME"手机卫士");
    
    // 2、指定快捷方式激活的意图
    // Intent value = new Intent(this,HomeActivity.class);
    Intent value = new Intent();
    value.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    value.addCategory(Intent.CATEGORY_DEFAULT);
    intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, value);
    
    // 3、快捷方式的图标:不指定的话默认为当前应用的图标
    intent.putExtra(Intent.EXTRA_SHORTCUT_ICON,BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
    
    // 4、指定不可创建多个快捷图标
    intent.putExtra("duplicate"false);
    sendBroadcast(intent);
    
}
注意: intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,null);这个不要用,很多手机不支持,导致为空图标
问题1:桌面快捷方式,必须是隐式的意图,如果是显示的意图,桌面会找不到要激活的意图,如下问题
解决:将要激活的意图设置为隐式意图
问题2:多次启动程序,每次都创建一个图标
解决:查看系统桌面应用注册的广播接收者
\aosp_jb422\packages\apps\Launcher2\src\com\android\launcher2\InstallShortcutReceiver.java
a) AndroidManifest.xml查看桌面注册的广播
<!-- Intent received used to install shortcuts from other applications -->
<receiver
    android:name="com.android.launcher2.InstallShortcutReceiver"
    android:permission="com.android.launcher.permission.INSTALL_SHORTCUT">
    <intent-filter>
        <action android:name="com.android.launcher.action.INSTALL_SHORTCUT" />
    </intent-filter>
</receiver>
b) 在InstallShortcutReceiver类中
private static boolean installShortcut(){}
// By default, we allow for duplicate entries (located in different places),默认允许安装多个图标入口
boolean duplicate = data.getBooleanExtra(Launcher.EXTRA_SHORTCUT_DUPLICATE, true);
c) 在Launcher类中:
static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
d) 加上这个,就可以解决多次创建快捷图标
intent.putExtra("duplicate"false);