Android快捷方式的創建與shortcut是否已創建的判斷

在Activity觸發事件中調用以下方法:

private void creatShortcut(){
		Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
				getString(R.string.app_name));
		shortcutIntent.putExtra("duplicate", false);		//不允許重複創建
		Intent intent = new Intent(Intent.ACTION_MAIN);
//		intent.setComponent(new ComponentName(MainPageActivity.this.getPackageName(),  
//		        ".activity.StartActivity"));   //此方式會導致4.0以上系統出現“未安裝此應用程序”錯誤,原因不詳,知道的同學望告知
		intent.setClass(MainPageActivity.this, StartActivity.class);

		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
				Intent.ShortcutIconResource.fromContext(MainPageActivity.this,
						R.drawable.icon));
		sendBroadcast(shortcutIntent);
	}

接下來在配置文件中加入:

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

/**
	 * 判斷快捷方式是否已經創建
	 */
	public static boolean hasShortcut(Context context) {
	    boolean result = false;
	    // 獲取當前應用名稱
	    String title = null;
	    try {
	        final PackageManager pm = context.getPackageManager();
	        title = pm.getApplicationLabel(
	                pm.getApplicationInfo(context.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 = context.getContentResolver().query(CONTENT_URI, null,
	            "title=?", new String[] { title }, null);
	    if (c != null && c.getCount() > 0) {
	        result = true;
	    }
	    return result;
	}

以上方法需要以下權限:

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


發佈了39 篇原創文章 · 獲贊 9 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章