android 创建桌面快捷方式的时候设置应用名称和图标是完全没有问题,但是点击快捷方式的时候出现“您的手机上未安装应用程序“,这是快捷方式的执行目标设置错误,也就是启动Activity。有些应用的启动Activity是欢迎界面,创建快捷方式的代码在其他的Activity里。
设置名称和图标
Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
//设置快捷方式名称
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
shortcut.putExtra("duplicate", false); // 不允许重复
//设置快捷方式图标
ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(context, R.drawable.ic_launcher);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
快捷方式是通过 Intent启动应用,下面是Intent方法中set打头的方法。
这里通过setClassName设置,不管在哪个Activity里写创建快捷方式的代码,只要拿到启动Activity的类名就可以。
在启动Activity里写创建快捷方式的代码
Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
shortcutIntent.setClassName(this, this.getClass().getName());
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
在非启动Activity里写创建快捷方式的代码
注意: 如果启动Activity直接写字符串,则前面必须加点(.)
例1:通过对象获取启动Activity类名(下面假设启动Activity的类名是SplashActivity)
Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
shortcutIntent.setClassName(this, SplashActivity.class.getName());
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
例2:直接写字符串
Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
shortcutIntent.setClassName(this, ".SplashActivity"); //不要忘了前面加点
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
例3:包名也写字符串
Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
shortcutIntent.setClassName("com.myapp.test", ".SplashActivity");
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
也可以这么写,道理都一样,只要明确启动Activity就可以
ComponentName comp = new ComponentName(this, SplashActivity.class.getName());
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));
最后广播
sendBroadcast(shortcut);
最后留下全部代码,方便复制,^-^
Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT"); //设置快捷方式名称 原创:http://www.cnblogs.com/androidheart shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name)); shortcut.putExtra("duplicate", false); // 不允许重复 //设置快捷方式图标 ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(context, R.drawable.ic_launcher); shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes); Intent shortcutIntent = new Intent(Intent.ACTION_MAIN); shortcutIntent.setClassName("com.myapp.test", ".SplashActivity"); shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); sendBroadcast(shortcut);
这里只是对“未安装应用程序”的解决方法的一种情况,其他的情况我暂时没有碰到,如果有人遇到别的情况,请给我留言。