分析桌面程序的源码发现具有接收创建桌面快捷图标的广播接受,创建快捷突变即发送广播的方式来实现的。下面来分析创建桌面快捷图标的过程。
1. 在应用程序的第一个Activity,添加创建快捷图标的方法, installShortCut();
// 创建桌面快捷图标
private void intallShotCut() {
// 定义广播通知桌面创建快捷图标
Intent intent = new Intent();
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");// 指定意图
// 设置动作(快捷方式的名称、图标)
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "助手");
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, BitmapFactory.decodeResource(getResources(), R.drawable.icon));
// 设置开启意图
Intent homeIntent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, homeIntent);
sendBroadcast(intent);// 发送创建快捷图标的广播
}
记得添加权限
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
2. 发现创建桌面快捷图标后并没有绑定打开我们的程序,什么原因呢?
因为桌面应用和我们的程序是不同的应用程序,说以不能使用显式意图,只能使用隐式意图。
桌面Activity的清单文件作如下配置:
<activity android:name="com.kevin.helper.activities.HomeActivity" >
<intent-filter>
<action android:name="com.kevin.helper.home" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
installShortCut();修改为:
// 创建桌面快捷图标
private void intallShotCut() {
// 定义广播通知桌面创建快捷图标
Intent intent = new Intent();
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");// 指定意图
// 设置动作(快捷方式的名称、图标)
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "助手");
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, BitmapFactory.decodeResource(getResources(), R.drawable.icon));
// 设置隐式开启意图
Intent homeIntent = new Intent();
homeIntent.setAction("com.kevin.helper.home");
homeIntent.addCategory("android.intent.category.DEFAULT");
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, homeIntent);
sendBroadcast(intent);// 发送创建快捷图标的广播
}
3. 但是有一个小BUG,每次进入程序都会在桌面创建一个快捷图标。记录住是否第一次运行程序
最终代码清单如下:
// 创建桌面快捷图标
private void intallShotCut() {
boolean installedshortcut = sp.getBoolean("installedshortcut", false);
if(installedshortcut) {
return;
}
// 定义广播通知桌面创建快捷图标
Intent intent = new Intent();
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");// 指定意图
// 设置动作(快捷方式的名称、图标)
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "助手");
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, BitmapFactory.decodeResource(getResources(), R.drawable.icon));
// 设置隐式开启意图
Intent homeIntent = new Intent();
homeIntent.setAction("com.kevin.helper.home");
homeIntent.addCategory("android.intent.category.DEFAULT");
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, homeIntent);
sendBroadcast(intent);// 发送创建快捷图标的广播
// 保存安装快捷图标信息
Editor editor = sp.edit();
editor.putBoolean("installedshortcut", true);
editor.commit();
}
桌面Activity的清单文件作如下配置:
<activity android:name="com.kevin.hepler.activities.HomeActivity" >
<intent-filter>
<action android:name="com.kevin.hepler.home" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
记得添加权限
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
浙公网安备 33010602011771号