您的位置:首页 > 移动开发 > Android开发

android自动添加程序桌面快捷方式

2014-01-10 10:25 519 查看
首先:

1、AndroidManifest.xml需要添加:
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"/> 如果需要在长按menu当中添加程序快捷方式则另外需要添加一个
<intent-filter>
<action android:name="android.intent.action.CREATE_SHORTCUT"></action>
</intent-filter>

2、需要在那个界面显示创建快捷方式就卸载对应的activity当中:

需要在oncreat()方法中判断是否已经创建快捷方式
boolean     flag =isShortcutInstalled();//如果已经创建,则不需要在创建
if(flag==false){
AlertDialog.Builder builder = new Builder(WelcomeActivity.this);
builder.setTitle("是否为此应用创建桌面快捷方式");
builder.setPositiveButton("是", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
addShortcutToDesktop();
}
});
builder.setNegativeButton("否", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
接着就是设置一些程序的版本和相关信息的方法了,这个可以自定义操作:
private void addShortcutToDesktop() {

Intent shortcut = new Intent(
"com.android.launcher.action.INSTALL_SHORTCUT");
// 不允许重建
shortcut.putExtra("duplicate", false);
// 设置名字
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, "加菲快捷");
// 设置图标
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(this,R.drawable.ico));
// 设置意图和快捷方式关联程序
Intent intent = new Intent(this, this.getClass());
// 桌面图标和应用绑定,卸载应用后系统会同时自动删除图标
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");

shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);

// 发送广播
sendBroadcast(shortcut);

}

/**
* 快捷方式信息是保存在com.android.launcher的launcher.db的favorites表中
*
* @return
*/
public boolean isShortcutInstalled() {
boolean isInstallShortcut = false;
final ContentResolver cr = LauncherDemo2Activity.this
.getContentResolver();
// 2.2系统是”com.android.launcher2.settings”,网上见其他的为"com.android.launcher.settings"
String AUTHORITY = null;
/*
* 根据版本号设置Uri的AUTHORITY
*/
if(getSystemVersion()>=8){
AUTHORITY = "com.android.launcher2.settings";
}else{
AUTHORITY = "com.android.launcher.settings";
}

Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/favorites?notify=true");
Cursor c = cr.query(CONTENT_URI,
new String[] { "title", "iconResource" }, "title=?",
new String[] { getString(R.string.app_name) }, null);// XXX表示应用名称。
if (c != null && c.getCount() > 0) {
isInstallShortcut = true;
System.out.println("已创建");
}
return isInstallShortcut;
}

/**
* 获取系统的SDK版本号
* @return
*/
private int getSystemVersion(){
return Build.VERSION.SDK_INT;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: