通过Intent在Android中创建快捷方式

7

可能重复:
在Android主屏幕上创建快捷方式

我在我的 Activity(HomeActivity.class)中有一个 TextView 和一个 Button

目标:当我点击 Button 时,它应该创建一个快捷方式,使用默认的 Android 图像作为图标,并将文本输入到 TextView 中。

到目前为止,我已经发现我们可以使用 ACTION_CREATE_SHORTCUT 创建快捷方式。

这是我到目前为止的代码:

Intent result = new Intent(android.content.Intent.ACTION_CREATE_SHORTCUT);
result.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
                new Intent(getApplicationContext(), Editor.class));
result.putExtra(TodoDbAdapter.KEY_ROWID,rowid);
result.putExtra(Intent.EXTRA_SHORTCUT_NAME,textView.getText());
result.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                Intent.ShortcutIconResource.fromContext(HomeActivity.this,
                                                        R.drawable.icon));
setResult(RESULT_OK, result);

我的清单文件:
<activity android:name=".HomeActivity" android:label="@string/app_name">

        <intent-filter>
                <action android:name="android.intent.action.CREATE_SHORTCUT" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

但这段代码并不会创建任何快捷方式。
我该如何创建快捷方式?

1
我认为你应该看一下这个页面。这也可能是这个问题或者这个问题的重复。 - N-JOY
1个回答

18

试一下这个:

Intent shortcutIntent;
shortcutIntent = new Intent();
shortcutIntent.setComponent(new ComponentName(activity.getPackageName(), ".classname"));

shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

final Intent putShortCutIntent = new Intent();
putShortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);

// Sets the custom shortcut's title
putShortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,"Title");
putShortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(PersonProfile.this, R.drawable.icon));
putShortCutIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
sendBroadcast(putShortCutIntent);

并将此权限添加到清单文件中:

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

对我不起作用。这个还有效吗? - toto_tata
@CapDroid:即使已经存在快捷方式,这也会创建一个新的。我们能否以一种方式创建快捷方式,使其替换现有的快捷方式而不是重复创建?请指导。 - Mudassir
@CapDroid:这只是针对原生启动器吗?还是用户设置为默认的任何启动器都可以? - Kamran Ahmed
2
这在Android 8.0及以上版本上不起作用。相反,您需要使用以下内容:https://developer.android.com/reference/android/support/v4/content/pm/ShortcutManagerCompat.html#requestPinShortcut(android.content.Context, android.support.v4.content.pm.ShortcutInfoCompat, android.content.IntentSender) - android developer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接