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

Kar*_*iya 7 android homescreen android-layout

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

我有一个TextViewButton我的Activity(HomeActivity.class).

目标:当我点击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);
Run Code Online (Sandbox Code Playgroud)

我的清单文件:

<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>
Run Code Online (Sandbox Code Playgroud)

但是这段代码不会创建任何快捷方式.

我该如何创建快捷方式?

Nir*_*tel 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);
Run Code Online (Sandbox Code Playgroud)

并在清单中添加此权限:

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
Run Code Online (Sandbox Code Playgroud)

  • 这不适用于 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)` (2认同)