android創建桌面快捷方式,適配8.0,避免重複創建

直接上代碼,可直接複製使用

    //創建桌面快捷方式
    private void createShortCut() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String shortcutId = "com.itx.shortcut";
            boolean isExit = false;
            ShortcutManager shortcutManager = (ShortcutManager) getSystemService(Context.SHORTCUT_SERVICE);
            for (ShortcutInfo info : shortcutManager.getPinnedShortcuts()) {
                if (shortcutId.equals(info.getId())) {
                //判斷快捷方式是否已存在
                    isExit = true;
                }
            }
            if (!isExit && shortcutManager.isRequestPinShortcutSupported()) {
                Uri content_url = Uri.parse("http://www.baidu.com/");
                Intent shortcutInfoIntent = new Intent(Intent.ACTION_VIEW, content_url);
                shortcutInfoIntent.setAction(Intent.ACTION_VIEW);
                ShortcutInfo info = new ShortcutInfo.Builder(this, shortcutId)
                        .setIcon(Icon.createWithResource(this, R.drawable.ibiguo_float))
                        .setShortLabel("快捷方式名字")
                        .setIntent(shortcutInfoIntent)
                        .build();
                shortcutManager.requestPinShortcut(info, null);
            }
        } else {
            Intent intentAddShortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
            intentAddShortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, "快捷方式名字");
            intentAddShortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                    Intent.ShortcutIconResource.fromContext(this,
                            R.drawable.ibiguo_float));//設置Launcher的Uri數據
            intentAddShortcut.putExtra("duplicate", false);
            Intent intentLauncher = new Intent();
            Uri content_url = Uri.parse("http://www.baidu.com/");
            intentLauncher.setData(content_url);
            intentAddShortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intentLauncher);
            sendBroadcast(intentAddShortcut);
        }
    }
發佈了22 篇原創文章 · 獲贊 12 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章