Android中创建和检测快捷方式

public class ShortcutUtil {

	/**
	 * 创建快捷方式
	 * 
	 * @param context
	 */
	public static void createShortcut(Context context, Class<?> target) {
		// <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
		Intent intent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
		intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(context, R.drawable.icon));
		intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getString(R.string.app_name));
		intent.putExtra("duplicate", false);
		Intent sIntent = new Intent(Intent.ACTION_MAIN);
		sIntent.addCategory(Intent.CATEGORY_LAUNCHER);// 加入action,和category之后,程序卸载的时候才会主动将该快捷方式也卸载
		sIntent.setClass(context, target);
		intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, sIntent);
		context.sendBroadcast(intent);
	}

	/**
	 * 判断桌面上是否有的快捷方式
	 * 
	 * @return
	 */
	public static boolean hasShortcut(Context context) {
		final ContentResolver cr = context.getContentResolver();
		final String AUTHORITY = "com.android.launcher.settings";
		final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true");
		// <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"/>
		Cursor c = cr.query(CONTENT_URI, new String[] { "intent" }, null, null, null);
		if (c == null) {
			// 注: 2.1update和2.2版本的真机上测试无法访问com.android.launcher.settings,2.1update1的模拟器上可以
			// ERROR/ActivityThread(1136): Failed to find provider info for com.android.launcher.settings
			return false;
		}
		while (c.moveToNext()) {
			String intentstring = c.getString(c.getColumnIndex("intent"));
			if (intentstring == null) {
				continue;
			}
			String componentString = getComponentString(intentstring);
			if (componentString.startsWith(context.getPackageName())) {
				return true;
			}
		}
		return false;
	}

	private static String getComponentString(String intentInfo) {
		// intent info 的格式:intent=#Intent;action=android.intent.action.MAIN;category=android.intent.category.LAUNCHER;launchFlags=0x10200000;component=com.allstar.tanzhi/.activities.StartActivity;end
		int start = intentInfo.indexOf("component") + 9 + 1;
		int end = intentInfo.indexOf(";", start);
		return intentInfo.substring(start, end);
	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值