添加快捷方式
private void addShortcut(String name) { // 设置关联程序 Intent launcherIntent = new Intent(this, SplashActivity.class); launcherIntent.setAction(Intent.ACTION_MAIN); launcherIntent.addCategory(Intent.CATEGORY_LAUNCHER); Intent addShortcutIntent = new Intent(); addShortcutIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); // 不允许重复创建 addShortcutIntent.putExtra("duplicate", false); // 名字 addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); // 图标 addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(SplashActivity.this, R.drawable.icon)); addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent); // 发送广播 sendBroadcast(addShortcutIntent); }
不要忘了在manifest中添加权限哦
<!-- 添加快捷方式 --> <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" /> <!-- 移除快捷方式 --> <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" /> <!-- 查询快捷方式 --> <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
这样程序在第一次运行的时候会自动创建快捷方式,以后每次启动的时候会提示已创建快捷方式,这样会觉得很烦,所以我在程序中做了下面的操作:
SharedPreferences sharedPraferences = getSharedPreferences("com.rosevision.ofashion", Context.MODE_PRIVATE); if (sharedPraferences.getInt("addShortcut", 0) == 0) { addShortcut(getResources().getString(R.string.app_name)); sharedPraferences.edit().putInt("addShortcut",1).apply(); }
这样处理以后,程序只有在每一次运行的时候自动创建快捷方式,以后每次启动的时候会判断是否已经创建了快捷方式,如果没有的话再去创建