【it168技术】android在桌面上生成快捷方式有两种情况,一种是直接在桌面直接生成;一种是长按桌面,在弹出的快捷菜单中生成。
谈谈在桌面上直接生成。个人觉得这个比较爽快,既然都是快捷方式了干嘛还要再隐藏一层呢?当然喜欢桌面干净的就比较喜欢第二个了。
第一个是通过广播(broadcast)的形式向luncher发送请求生成快捷方式的。
在网上找到关于这方面的注册信息。
<!--设置wallpapaer的activity -->
<!-- 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>
可以看出,要在桌面上创建快捷方式就需要权限了:
android:permission="com.android.launcher.permission.install_shortcut。
所以在我们的manifest.xml文件中,我们需要加入下面这段话:
<uses-permission android:name="com.android.launcher.permission.install_shortcut"/>
下面就是代码层的实现:
假如我在一个activity中创建一个创建快捷方式的方法:createshortcut();
public void createshortcut(){
//创建快捷方式的intent
intent shortcutintent = new intent("com.android.launcher.action.install_shortcut");
//不允许重复创建
shortcutintent.putextra("duplicate", false);
//需要现实的名称
shortcutintent.putextra(intent.extra_shortcut_name, getstring(r.string.shortcutname));
//快捷图片
parcelable icon = intent.shortcuticonresource.fromcontext(getapplicationcontext(), r.drawable.icon);
shortcutintent.putextra(intent.extra_shortcut_icon_resource, icon);
//点击快捷图片,运行的程序主入口
shortcutintent.putextra(intent.extra_shortcut_intent, new intent(getapplicationcontext() , enteractivity.class));
//发送广播。ok
sendbroadcast(shortcutintent);
}
二、长按桌面弹出的桌面快捷方式创建
第一页谈过直接在桌面生成快捷方式,现在说说如何在添加到一个shortcuts列表中,就是你长按桌面弹出来的那个东东。
首先在注册activity时,需要添加一个action为android.intent.action.create_shoertcut的intentfilter.如下所示:
<activity android:name="shortcuttest">
<action android:name="android.intent.action.create_shortcut"/>
</activity>
接下来就是就是设置快捷方式的图标、名称、事件等属性。这里图表的生成,android里提供了专门的方法来生成。
public class shortcuttest extends activity{
@override
protected void oncreate(bundle savedinstancestate) {
// todo auto-generated method stub
super.oncreate(savedinstancestate);
}
public void createshortcut(){
intent addshortcut;
//判断是否需要添加快捷方式
if(getintent().getaction().equals(intent.action_create_shortcut)){
addshortcut = new intent();
//快捷方式的名称
addshortcut.putextra(intent.extra_shortcut_name , "我的快捷方式");
//显示的图片
parcelable icon = shortcuticonresource.fromcontext(this, r.drawable.icon);
addshortcut.putextra(intent.extra_shortcut_icon_resource, icon);
//快捷方式激活的activity,需要执行的intent,自己定义
addshortcut.putextra(intent.extra_shortcut_intent, new intent());
//ok,生成
setresult(result_ok, addshortcut);
}else{
//取消
setresult(result_canceled);
}