如何实现添加快捷图标?

Launcher为了让其他应用程序能够定制自己的快捷图标,就注册了一个BroadcastReceiver专门接收其他应用程序发来的快捷图标 定制信息。所以只需要根据该BroadcastReceiver构造出相对应的Intent并装入我们的定制信息,最后调用sendBroadcast方 法就可以创建一个快捷图标了。那么,要构造怎样一个Intent才会被Launcher的BroadcastReceiver接收呢?我们还是先来看看这 个BroadcastReceiver的注册信息吧。
下面是Launcher的AndroidManifest.xml文件中Install-ShortcutReceiver的注册信息。
<!– Intent received used to install shortcuts from other applications –>
<receiver
android:name=”.InstallShortcutReceiver”
android:permission= “com.android.launcher.permission.INSTALL_SHORTCUT”>
<intent-filter>
<action android:name=”com.android.launcher.action.INSTALL_SHORTCUT” />
</intent-filter>
</receiver>

如何向这个 BroadcastReceiver 发送广播,设置如下:

  1. 首先应用程序必须要有com.android.launcher.permission.INSTALL_SHORTCUT权限;
  2. 然后广播出去的Intent的action设置com.android.launcher.action.INSTALL_SHORTCUT;
  3. 这样广播就可以发送给Launcher的InstallShortcutReceiver了;

而快捷图标的信息则是以附加信息的形式存储在广播出去的Intent对象中的,包括有图标、显示的名称以及用来启动目标组件的Intent这三种信息。我们可以通过putExtra的重载方法,通过指定相应的键值,将这些信息放到附加信息的Bundle对象中。

列出了各种快捷图标信息相对应的键值和数据类型:

shortcut

下面举些具体的例子,如下:

private final String ACTION_ADD_SHORTCUT =
“com.android.launcher.action.INSTALL_SHORTCUT”;
Intent addShortcut =new Intent(ACTION_ADD_SHORTCUT);
String numToDial = null;
Parcelable icon = null;

numToDial = “110″;
icon = Intent.ShortcutIconResource.fromContext(this,R.drawable.jing);

//numToDial = “119″;
//icon = Intent.ShortcutIconResource.fromContext(this,R.drawable.huo);

//图标
addShortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,icon);

//名称
addShortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,numToDial);

//启动目标组件的Intent
Intent directCall;
directCall.setData(Uri.parse(”tel://”+numToDial));
addShortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT,directCall);
sendBroadcast(addShortcut);
上面的程序运行后的界面如下:
110-119

总结说明

只要知道这些信息后,你就可以轻而易举的为应用程序添加快捷图标。