Android实现向桌面添加快捷方式的代码

2014-09-06 14:02:15来源:fengyuzhengfan的专栏作者:CrazyCodeBoy

对于一个希望拥有更多用户的应用来说,用户桌面可以说是所有软件的必争之地,如果用户在手机桌面上建立了该软件的快捷方式,用户将会更频繁地使用该软件。因此,所有 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" />

关键词:Android