PS:看了9年的小说,自己开始动手写了一本,请各位猿们动动手指,点击下,有起点账号的可以收藏下!!《武意长存》
我们经常会有这么一个需求,当用户第一次安装app时,创建一个桌面快捷图标,之后则不再创建
以下是Android桌面app的manifest的部分源码
<!-- 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>
创建快捷图标,我们需要添加权限
<pre name="code" class="html"><uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
具体实现代码如下
<span style="white-space:pre"> </span>private void createShortcut() {
//发送广播的意图,告诉桌面要创建快捷图标了
Intent intent = new Intent();
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
//快捷方式 要包含3个重要的信息 1.名称 2.图标 3.干什么
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
Intent shortcutIntent = new Intent();
shortcutIntent.setAction("android.intent.action.MAIN");
shortcutIntent.addCategory("android.intent.category.LAUNCHER");
shortcutIntent.setClassName(this, "com.blank.shortcut.MainActivity");
// 不允许重复创建
shortcutIntent.putExtra("duplicate", false);
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
sendBroadcast(intent); //发送广播,用于生成快捷图标
}
虽然我们在上面的代码设置了不允许重复创建快捷图标
// 不允许重复创建
shortcutIntent.putExtra("duplicate", false);
但我们却会发现,该行代码并没有产生效果,每当调用一次就会创建一个快捷图标。
因此,我们只能自己保存一个字段用于判断
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
Editor editor = sp.edit();
boolean shortcut = sp.getBoolean("shortcut", false);
if(!shortcut) {
createShortcut();
editor.putBoolean("shortcut", true);
editor.commit();
}
}
这样就保证了只有第一次安装app时才会创建快捷图标