Android_如何为一个app创建桌面快捷方式

PS:看了9年的小说,自己开始动手写了一本,请各位猿们动动手指,点击下,有起点账号的可以收藏下!!《武意长存》

我们经常会有这么一个需求,当用户第一次安装app时,创建一个桌面快捷图标,之后则不再创建

以下是Android桌面appmanifest的部分源码

 <!-- 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时才会创建快捷图标



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值