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

Android应用程序快捷方式操作(添加,删除,判断是否存在)

2014-03-09 14:31 721 查看
Android中,程序的桌面快捷方式展示很有必要,桌面的一个入口点。自己按照网上例子参考了很久,发现删除快捷方式很多时候存在问题:

        可能和第三方的桌面等因素有点关系吧(不确定)

这里推荐大家参考的代码,在Android4.2.1系统中测试有效,其他问题还未测试。

文章转载:http://orgcent.com/android-add-del-shortcut-desktop/

 

1、添加桌面快捷方式

/**
* 为当前应用添加桌面快捷方式
*/
public static void addShortcut(Context cx) {
Intent shortcut = new Intent(
"com.android.launcher.action.INSTALL_SHORTCUT");

Intent shortcutIntent = cx.getPackageManager()
.getLaunchIntentForPackage(cx.getPackageName());
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
// 获取当前应用名称
String title = null;
try {
final PackageManager pm = cx.getPackageManager();
title = pm.getApplicationLabel(
pm.getApplicationInfo(cx.getPackageName(),
PackageManager.GET_META_DATA)).toString();
} catch (Exception e) {
}
// 快捷方式名称
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
// 不允许重复创建(不一定有效)
shortcut.putExtra("duplicate", false);
// 快捷方式的图标
Parcelable iconResource = Intent.ShortcutIconResource.fromContext(cx,
R.drawable.ic_launcher);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);

cx.sendBroadcast(shortcut);
}


2、删除快桌面捷方式

 /**
* 删除当前应用的桌面快捷方式
*/
public static void delShortcut(Context cx) {
Intent shortcut = new Intent(
"com.android.launcher.action.UNINSTALL_SHORTCUT");

// 获取当前应用名称
String title = null;
try {
final PackageManager pm = cx.getPackageManager();
title = pm.getApplicationLabel(
pm.getApplicationInfo(cx.getPackageName(),
PackageManager.GET_META_DATA)).toString();
} catch (Exception e) {
}
// 快捷方式名称
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
Intent shortcutIntent = cx.getPackageManager()
.getLaunchIntentForPackage(cx.getPackageName());
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
cx.sendBroadcast(shortcut);
}

 

3、判断桌面快捷方式是否存在

 /**
* 判断桌面是否已添加快捷方式
*
*/
public static boolean hasShortcut(Context cx) {
boolean result = false;
// 获取当前应用名称
String title = null;
try {
final PackageManager pm = cx.getPackageManager();
title = pm.getApplicationLabel(
pm.getApplicationInfo(cx.getPackageName(),
PackageManager.GET_META_DATA)).toString();
} catch (Exception e) {
}

final String uriStr;
if (android.os.Build.VERSION.SDK_INT < 8) {
uriStr = "content://com.android.launcher.settings/favorites?notify=true";
} else {
uriStr = "content://com.android.launcher2.settings/favorites?notify=true";
}
final Uri CONTENT_URI = Uri.parse(uriStr);
final Cursor c = cx.getContentResolver().query(CONTENT_URI, null,
"title=?", new String[] { title }, null);
if (c != null && c.getCount() > 0) {
result = true;
}
return result;
}

 

4、最后添加相应的操作权限(4.0以上的系统可能不需要):

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息