如何在Android 8的主屏幕上创建快捷方式?

时间:2017-11-18 15:56:22

标签: java android android-8.0-oreo

我将在Android 8的主屏幕上创建快捷方式并使用ShortcutManager它在上下文菜单中创建快捷方式,用户应在主屏幕上手动拖动快捷方式,而在主屏幕上自动创建的较低的Android 8中 我的代码是:

ShortcutManager sM = (ShortcutManager) getSystemService(SHORTCUT_SERVICE);


Intent intent1 = new Intent(getApplicationContext(), MasterActivity.class);
intent1.setAction(Intent.ACTION_VIEW);


ShortcutInfo shortcut1 = new ShortcutInfo.Builder(this, "shortcut1")
    .setIntent(intent1)
    .setLongLabel("Ayande")
    .setShortLabel("This is the Ayandeh")
    .setDisabledMessage("Login to open this")
    .setIcon(Icon.createWithResource(this, R.drawable.ayandeh))
    .build();

sM.addDynamicShortcuts(Arrays.asList(shortcut1));

结果:

enter image description here

但结果我想自动创建快捷方式:

enter image description here

2 个答案:

答案 0 :(得分:0)

想出来。使用ShortcutManager.requestPinShortcut。但请注意,该方法将打开一个对话框,询问用户是否将快捷方式添加到主屏幕。对我来说不幸的是,这个对话框在其他活动背后开放,因此从未见过!

答案 1 :(得分:0)

您可以使用此方法

private void createShortcut() {
    ShortcutManager shortcutManager = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N_MR1) {
        shortcutManager = mContext.getSystemService(ShortcutManager.class);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        if (shortcutManager != null) {
            if (shortcutManager.isRequestPinShortcutSupported()) {
                ShortcutInfo shortcut = new ShortcutInfo.Builder(mContext, uniqueid)    
                        .setShortLabel("Demo")
                        .setLongLabel("Open the Android Document")
                        .setIcon(Icon.createWithResource(mContext, R.drawable.andi))
                        .setIntent(new Intent(Intent.ACTION_VIEW,
                                Uri.parse("https://stackoverflow.com")))
                        .build();

                shortcutManager.requestPinShortcut(shortcut, null);
            } else
                Toast.makeText(mContext, "Pinned shortcuts are not supported!", Toast.LENGTH_SHORT).show();
        }
    }
}