Android小技巧之創建桌面快捷方式(已適配8.0)

前言

        在某些情況下需要對應用創建桌面快捷方式,特別是在使用原生系統(4.3到8.0)運行物聯網app時,往往存在二級菜單,而應用圖標默認安裝在二級菜單(現在國內主流手機廠商的系統都沒有二級菜單了),如果按照網上的做法是可以創建和兼容8.0系統,但存在一個問題:

         點擊快捷方式打開應用和點擊二級菜單應用圖標打開應用,會出現重啓應用的問題,導致兩邊進入應用顯示的頁面內容不一致,體驗極不友好,比如:通過快捷方式進入應用並經過一系列操作進入到看某網紅直播的頁面,然後按home鍵,進入系統二級菜單點擊了應用圖標,這時發現應用重啓,真操蛋。 

解決方法

爲 快捷方式意圖設置如下代碼即可:

        shortcutInfoIntent.setClassName(activity, activity.getClass().getName());
        shortcutInfoIntent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        shortcutInfoIntent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
        shortcutInfoIntent.addCategory(Intent.CATEGORY_LAUNCHER);

這樣不管那邊啓動應用,兩邊界面內容一致

操作步驟

1.添加權限 

 <!--快捷方式-->
    <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" /><!-- 添加快捷方式 -->
    <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" /><!-- 移除快捷方式 -->
    <uses-permission android:name="android.permission.INSTALL_SHORTCUT" />
    <uses-permission android:name="android.permission.UNINSTALL_SHORTCUT" />
    <!-- 查詢快捷方式2.1以下 -->
    <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
    <uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS" />
    <!-- 查詢快捷方式4.4及以下 -->
    <uses-permission android:name="com.android.launcher2.permission.READ_SETTINGS" />
    <uses-permission android:name="com.android.launcher2.permission.WRITE_SETTINGS" />
    <!-- 查詢快捷方式4.4以上 -->
    <uses-permission android:name="com.android.launcher3.permission.READ_SETTINGS" />
    <uses-permission android:name="com.android.launcher3.permission.WRITE_SETTINGS" />

 2.使用工具類在啓動頁操作

該工具類已經適配4.3到8.0快捷方式創建

package com.sjl.core.util;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

/**
 * 快捷方式創建工具類
 *
 * @author Kelly
 * @version 1.0.0
 * @filename ShortcutUtils.java
 * @time 2019/5/28 17:35
 * @copyright(C) 2019 song
 */
public class ShortcutUtils {
    private static final String TAG = "ShortcutUtils";

    /**
     * 添加桌面圖標快捷方式
     *
     * @param activity Activity對象,設置要啓動的activity,一般都是應用入口類
     * @param nameId   快捷方式名稱id
     * @param iconId   圖標資源id
     */
    public static void addShortcut(Activity activity, int nameId, int iconId) {
        Bitmap bitmap = BitmapFactory.decodeResource(activity.getResources(), iconId, null);
        addShortcut(activity, activity.getResources().getString(nameId), bitmap);
    }


    /**
     * 添加桌面圖標快捷方式
     *
     * @param activity Activity對象
     * @param name     快捷方式名稱
     * @param icon     快捷方式圖標
     */
    public static void addShortcut(Activity activity, String name, Bitmap icon) {
        Intent shortcutInfoIntent = new Intent(Intent.ACTION_MAIN);
        /**
         * 點擊快捷方式回到應用,而不是重新啓動應用,解決系統一級菜單和二級菜單進入應用不一致問題
         */
        shortcutInfoIntent.setClassName(activity, activity.getClass().getName());
        shortcutInfoIntent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        shortcutInfoIntent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
        shortcutInfoIntent.addCategory(Intent.CATEGORY_LAUNCHER);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            if (isShortCutExist(activity, name)) {
                Log.w(TAG, "shortcut already exist.");
                return;
            }
            //  創建快捷方式的intent廣播
            Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
            // 添加快捷名稱
            shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
            //  快捷圖標是允許重複(不一定有效)
            shortcut.putExtra("duplicate", false);
            // 快捷圖標
            // 使用資源id方式
//            Intent.ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(activity, R.mipmap.icon);
//            shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
            // 使用Bitmap對象模式
            shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON, icon);
            // 添加攜帶的下次啓動要用的Intent信息
            shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutInfoIntent);
            // 發送廣播
            activity.sendBroadcast(shortcut);
        } else {
            ShortcutManager shortcutManager = (ShortcutManager) activity.getSystemService(Context.SHORTCUT_SERVICE);
            if (null == shortcutManager) {
                // 創建快捷方式失敗
                Log.e(TAG, "Create shortcut failed.ShortcutManager is null.");
                return;
            }
            shortcutInfoIntent.setAction(Intent.ACTION_VIEW); //action必須設置,不然報錯
            ShortcutInfo shortcutInfo = new ShortcutInfo.Builder(activity, name)
                    .setShortLabel(name)
                    .setIcon(Icon.createWithBitmap(icon))
                    .setIntent(shortcutInfoIntent)
                    .setLongLabel(name)
                    .build();
            shortcutManager.requestPinShortcut(shortcutInfo, PendingIntent.getActivity(activity,
                    0, shortcutInfoIntent, PendingIntent.FLAG_UPDATE_CURRENT).getIntentSender());
        }
    }


    /**
     * 判斷快捷方式是否存在
     *
     * @param context 上下文
     * @param title   快捷方式標誌,不能和其它應用相同
     * @return
     */
    public static boolean isShortCutExist(Context context, String title) {

        boolean isInstallShortcut = false;

        if (null == context || TextUtils.isEmpty(title))
            return isInstallShortcut;
        String authority = getAuthority();
        final ContentResolver cr = context.getContentResolver();
        if (!TextUtils.isEmpty(authority)) {
            try {
                final Uri CONTENT_URI = Uri.parse(authority);

              //  Cursor c = cr.query(CONTENT_URI, new String[]{"title", "iconResource"}, "title=?", new String[]{title.trim()},
                        null);

                Cursor c = cr.query(CONTENT_URI, new String[]{"title"}, "title=?", new String[]{title.trim()},
                        null);

                // XXX表示應用名稱。
                if (c != null && c.getCount() > 0) {
                    isInstallShortcut = true;
                }
                if (null != c && !c.isClosed())
                    c.close();
            } catch (Exception e) {
                Log.e(TAG, "isShortCutExist:" + e.getMessage());
            }
        }
        return isInstallShortcut;
    }

    public static String getAuthority() {
        String authority;
        int sdkInt = android.os.Build.VERSION.SDK_INT;
        if (sdkInt < 8) { // Android 2.1.x(API 7)以及以下的
            authority = "com.android.launcher.settings";
        } else if (sdkInt <= 19) {// Android 4.4及以下
            authority = "com.android.launcher2.settings";
        } else {// 4.4以上
            authority = "com.android.launcher3.settings";
        }
        return "content://" + authority + "/favorites?notify=true";
    }

}

3.代碼調用

        ShortcutUtils.addShortcut(SplashActivity.this, R.string.app_name, R.mipmap.ic_launcher);

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章