標籤:android style blog class code java
android判斷和建立捷徑(4.03測試通過)
整理了網上的建立方式的代碼,對於捷徑的判斷使用系統api擷取當前啟動器來處理,這樣系統定製過或者啟動器不一樣也沒關係 。
一加許可權和聲明目標activity
<!-- 建立捷徑 --> <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" /> <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
<activity android:name="com.shortcut.TestActivity" android:configChanges="keyboardHidden|orientation" android:theme="@android:style/Theme.Translucent" > <intent-filter> <action android:name="action.com.shortcut.test" /> </intent-filter> </activity>
二建立代碼
/** * 建立捷徑 * * @param context * @param name 顯示名稱 * @param url */public static void createShortCut(Context context, String name, String url) {if (hasShortCut(context, name)) { Log.v("createShortCut", name + "捷徑已存在");return;}final Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");shortcutIntent.putExtra("duplicate", false);final Parcelable icon = Intent.ShortcutIconResource.fromContext(context,ResourceUtil.getId(context, "drawable", "o2o_game_float_icon"));// 這個參數是啟動的activity的actionfinal Intent targetIntent = new Intent("action.com.shortcut.test");// 目標activitytargetIntent.setClassName(context.getPackageName(),"com.shortcut.TestActivity");targetIntent.putExtra("url", url);targetIntent.putExtra("name", name);targetIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, targetIntent);shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);context.sendBroadcast(shortcutIntent);}/** * 判斷捷徑是否已存在 * * @param context * @param name * @return */private static boolean hasShortCut(Context context, String name) {Log.v("LauncherPackageName",getLauncherPackageName(context));String launcherPackage = getLauncherPackageName(context);if (TextUtils.isEmpty(launcherPackage)) {// 查詢不到啟動器時預設已存在捷徑,不進行建立return true;}// Log.v("LauncherPackageName", launcherPackage);boolean result = false;final String uriStr = "content://" + launcherPackage+ ".settings/favorites?notify=true";final Uri CONTENT_URI = Uri.parse(uriStr);final Cursor c = context.getContentResolver().query(CONTENT_URI, null,"title=?", new String[] { name }, null);if (c != null && c.getCount() > 0) {result = true;}return result;}/** * 擷取正在運行案頭包名(註:存在多個案頭時且未指定預設案頭時,該方法返回"",使用時需處理這個情況) */private static String getLauncherPackageName(Context context) {final Intent intent = new Intent(Intent.ACTION_MAIN);intent.addCategory(Intent.CATEGORY_HOME);final ResolveInfo res = context.getPackageManager().resolveActivity(intent, 0);if (res.activityInfo == null) {// should not happen. A home is always installed, isn‘t it?return "";}if (res.activityInfo.packageName.equals("android")) {// 有多個傳統型程式存在,且未指定預設項時;return "";} else {return res.activityInfo.packageName;}}