Android开发之向桌面添加快捷方式
对于一个希望拥有更多用户的应用来说,用户桌面可以说是所有软件的必争之地,如果用户在手机桌面上建立了该软件的快捷方式,用户将会更频繁地使用该软件。因此,所有 Android程序都应该允许用户把软件的快捷方式添加到桌面上。
在程序中把一个软件的快捷方式添加到桌面上,只需要如下三步即可:
1. 创建一个添加快捷方式的Intent该Intent的Action属性值应该为com.android.launcher.action.INSTALLSHORTCUT,。
2. 通过为该Intent加Extra属性来设置快捷方式的标题、图标及快捷方式对应启动的程序。
3. 调用sendBroadcast()方法发送广播即可添加快捷方式。
实例代码:
- /**
- * 向桌面添加快捷方式
- * @author jph
- * Date:2014.09.05
- */
- public class AddShortcut extends Activity {
- Button btnAddShortCut;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.mian);
- btnAddShortCut=(Button)findViewById(R.id.btnAddShortCut);
- btnAddShortCut.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- //创建一个添加快捷方式的Intent
- Intent addSC=new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
- //快捷键的标题
- String title=getResources().getString(R.string.shotcut_title);
- //快捷键的图标
- Parcelable icon=Intent.ShortcutIconResource.fromContext(
- AddShortcut.this, R.drawable.ic_launcher);
- //创建单击快捷键启动本程序的Intent
- Intent launcherIntent=new Intent(AddShortcut.this, AddShortcut.class);
- //设置快捷键的标题
- addSC.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
- //设置快捷键的图标
- addSC.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
- //设置单击此快捷键启动的程序
- addSC.putExtra(Intent.EXTRA_SHORTCUT_INTENT,launcherIntent);
- //向系统发送添加快捷键的广播
- sendBroadcast(addSC);
- }
- });
- }
- }
最后为应用程序创建快捷键添加权限:
- <!-- 指定添加安装快捷方式的权限 -->
- <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
程序运行效果图:

-
顶
- 4
-
踩
本文介绍如何在Android应用中实现快捷方式添加到用户桌面的功能,包括创建Intent、设置快捷方式属性和发送广播等关键步骤,并提供实例代码以辅助理解。此外,文章还强调了为应用添加快捷方式的权限配置。
4168

被折叠的 条评论
为什么被折叠?



