ANdroid8.0以上创建快捷方式

26 篇文章 0 订阅

客户有在桌面上创建网页链接快捷方式的需求,以前做了一个APP有这个功能,今天试了一下,竟然不能用了。经查是7.1以下可以支持,8.0以上就不行了。于是全网查资料,还真不容易实现。好在google.cn的开发网有这个,记录一下,也方便新人。

创建固定快捷方式

在 Android 8.0(API 级别 26)及更高版本中,您可以创建固定快捷方式。与静态和动态快捷方式不同,固定快捷方式在受支持的启动器中显示为单独的图标。图 1 显示了这两类快捷方式之间的区别。

注意:当您尝试将快捷方式固定到受支持的启动器上时,用户会收到一个确认对话框,询问其是否允许固定该快捷方式。如果用户不允许固定该快捷方式,启动器会取消这一请求。

图 1. 应用快捷方式与固定快捷方式的外观

要将快捷方式固定到使用您的应用的受支持启动器上,请按顺序完成以下一系列步骤:

  1. 使用 isRequestPinShortcutSupported() 验证设备的默认启动器是否支持应用内固定快捷方式。
  2. 使用以下两种方式之一创建 ShortcutInfo 对象,具体采用哪种方式取决于是否已存在相应快捷方式:

    1. 如果已存在相应快捷方式,请创建仅包含现有快捷方式 ID 的 ShortcutInfo 对象。系统会自动找到与该快捷方式相关的所有其他信息,并将其固定。
    2. 如果您要固定原本不存在的新快捷方式,请创建包含新快捷方式 ID、intent 和简短标签的 ShortcutInfo 对象。

    注意:由于系统会自动对固定快捷方式执行备份和恢复操作,因此这些快捷方式的 ID 应包含稳定的常量字符串或服务器端标识符,而不是在本地生成的可能对其他设备毫无意义的标识符。

  3. 尝试通过调用 requestPinShortcut() 将快捷方式固定到设备的启动器上。在此过程中,您可以传入一个 PendingIntent 对象,用于仅在快捷方式成功固定后通知您的应用。

    注意:如果用户不允许将快捷方式固定到启动器上,您的应用就不会收到回调。

    快捷方式固定后,您的应用可以使用 updateShortcuts() 方法更新其内容。如需了解详情,请参阅更新快捷方式

以下代码段演示了如何创建固定快捷方式:

注意ShortcutManager 类的实例必须使用带有参数 ShortcutManager.class 的 Context.getSystemService(Class) 或带有参数 Context.SHORTCUT_SERVICE 的 Context.getSystemService(String) 来获取。

KotlinJava

ShortcutManager shortcutManager =
        context.getSystemService(ShortcutManager.class);

if (shortcutManager.isRequestPinShortcutSupported()) {
    // Assumes there's already a shortcut with the ID "my-shortcut".
    // The shortcut must be enabled.
    ShortcutInfo pinShortcutInfo =
            new ShortcutInfo.Builder(context, "my-shortcut").build();

    // Create the PendingIntent object only if your app needs to be notified
    // that the user allowed the shortcut to be pinned. Note that, if the
    // pinning operation fails, your app isn't notified. We assume here that the
    // app has implemented a method called createShortcutResultIntent() that
    // returns a broadcast intent.
    Intent pinnedShortcutCallbackIntent =
            shortcutManager.createShortcutResultIntent(pinShortcutInfo);

    // Configure the intent so that your app's broadcast receiver gets
    // the callback successfully.For details, see PendingIntent.getBroadcast().
    PendingIntent successCallback = PendingIntent.getBroadcast(context, /* request code */ 0,
            pinnedShortcutCallbackIntent, /* flags */ 0);

    shortcutManager.requestPinShortcut(pinShortcutInfo,
            successCallback.getIntentSender());
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值