您的位置:首页 > 移动开发 > Android开发

android--创建桌面快捷方式

2016-06-23 11:27 429 查看
在安装好了应用之后,一般都会自动在桌面创建快捷方式,这篇文章就总结一下在桌面创建快捷方式的方法。

一.查看Android桌面源码Launch下Manifest

<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>


这个广播接收者接收

android:name=”com.android.launcher.action.INSTALL_SHORTCUT” 这样一个action,接收到配置上述action的广播之后,系统会根据接收广播中Intent的内容,自动为我们创建桌面快捷方式。

所以在自己的应用中生成快捷方式的步骤如下:

1. new一个Intent action配置为com.android.launcher.action.INSTALL_SHORTCUT;

2. 给new出来的intent设置图标,名称,和点击之后的意图,用于桌面上快捷方式的展示和跳转。

3. 发送广播

4. 配置权限

具体如下。

二.配置相应的Intent并发送广播

下面以本渣渣的项目为例讲解:

实现的效果为:安装了应用之后,自动在桌面生成快捷方式,点击之后跳转到应用的HomeActivity界面。

//1.给intent设置图标,名称,点击后的意图
Intent intent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
//图标
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON,             BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));
//名称
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,"宇哥手机卫士");

//点击后的意图 跳转至HomeActivity 隐式意图
Intent shortCutIntent = newIntent("android.intent.action.HOME");
shortCutIntent.addCategory("android.intent.category.DEFAULT");
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,shortCutIntent );
//3.发送带数据的广播
sendBroadcast(intent);


注意:

1.在点击桌面快捷方式之后,要跳转到HomeActivity界面,所以通过隐式Intent打开这个界面。

在AndroidManifest文件中给HomeActivity配置 intent-fliter

<activity android:name="activity.HomeActivity">
<intent-filter>
<action android:name="android.intent.action.HOME"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>


2.由源码可以看到

android:permission="com.android.launcher.permission.INSTALL_SHORTCUT">


所以需要在AndroidManifest中添加相应的权限

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>


3.在发送广播的时候应该是

sendBroadcast(intent);


而不是

sendBroadcast(shortCutIntent);


intent:发送的广播的意图,其中配置了 图片,名称,和点击意图,也就是shortCutIntent。

shortCutIntent:点击桌面快捷方式之后所跳转的意图。

三.后记

本渣渣大三快结束了, 马上就要找工作了,正在努力准备下半年的秋招,暑假在犹豫,是呆在学校充电,还是出去找一份实习。。好纠结
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: