在主屏幕上创建特定活动的快捷方式

Juv*_*uvi 5 android shortcut intentfilter android-intent

我想为我的用户提供一个选项,可以在应用程序中创建特定页面的快捷方式.当你长按聊天时我在Whatsapp上看到了类似的用法,你可以创建这个特定聊天的桌面快捷方式.

我已经尝试找到有关此功能的一些文档,但无法使其正常工作.这就是我所拥有的:

不是启动器活动的活动(包括意图过滤器)

 <activity android:name="com.my.example.pages.Topics"
    android:parentActivityName="com.my.example.pages.Apps">
        <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)

createShortcut函数

 public void createShortcut(){
        Intent shortcutIntent = new Intent("com.my.example.pages.Topics");
        Intent.ShortcutIconResource iconResource = Intent.ShortcutIconResource.fromContext(getActivity(), R.drawable.app_logo);

        // The result we are passing back from this activity
        Intent intent = new Intent();
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Shortcut Test");
        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
        getActivity().setResult(getActivity().RESULT_OK, intent);
        getActivity().finish();

        Toast.makeText(getActivity(),"Shortcut created",Toast.LENGTH_SHORT).show();
    }
Run Code Online (Sandbox Code Playgroud)

表现

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

我可能错过了一些东西,因为在调用函数后我得到了Toasts但是没有创建快捷方式,并且应用程序因为finish()方法而退出.

为了更清楚 - 如何为非启动器活动创建快捷方式?

*我正在我的一个viewpager片段中运行代码.

Him*_*ora 7

使用此选项可为非启动器活动创建快捷方式.

    private void createShortcutOfApp() {

        Intent shortcutIntent = new Intent(getApplicationContext(),
            YourTargetActivity.class);
        shortcutIntent.setAction(Intent.ACTION_MAIN);

        Intent addIntent = new Intent();
        addIntent
            .putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "App shortcut name");
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
        Intent.ShortcutIconResource.fromContext(getApplicationContext(),
        R.mipmap.logo_of_your_app_shortcut));

        addIntent
            .setAction("com.android.launcher.action.INSTALL_SHORTCUT");
        addIntent.putExtra("duplicate", false);  //may it's already there so   don't duplicate
        getApplicationContext().sendBroadcast(addIntent);
    }
Run Code Online (Sandbox Code Playgroud)

现在在清单中添加权限

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

现在定义

android:exported="true"
Run Code Online (Sandbox Code Playgroud)

属性

<activity> tag 
Run Code Online (Sandbox Code Playgroud)

喜欢

<activity
  android:name=".YourTargetActivity"
  android:exported="true"></activity>
Run Code Online (Sandbox Code Playgroud)

这就像whatsapp app聊天快捷方式.