移动端添加桌面快捷方式实现

最近很多移动端都有添加桌面的快捷方式功能,产品小姐姐对此非常感兴趣,一定要做这个功能,所以,今天就来玩玩这个功能。

  • 直接上代码
    • Android 代码
// 小于 Android Oreo 版本不支持桌面创建快捷方式
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  ShortcutManager shortcutManager = (ShortcutManager) mContext.getSystemService(Context.SHORTCUT_SERVICE);
  if (shortcutManager != null && shortcutManager.isRequestPinShortcutSupported()) {
    Intent shortcutInfoIntent = new Intent(mContext, WebActivity.class);

    // 此处 xxx 是跳转到目标 web h5 的地址
    shortcutInfoIntent.putExtra("url", "xxx");

    // 此处 “标题” 是打开 webview 的标题
    shortcutInfoIntent.putExtra("title", "标题");
    shortcutInfoIntent.setAction(Intent.ACTION_VIEW);

    // 此处 “标题” 是桌面创建快捷方式的标题
    // 此处 R.drawable.icon_activity 是桌面创建快捷方式的 logo
    ShortcutInfo info = new ShortcutInfo.Builder(mContext, activityId).setIcon(Icon.createWithResource(mContext, R.drawable.icon_activity))
.setShortLabel("标题").setIntent(shortcutInfoIntent).build();
    PendingIntent shortcutCallbackIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(mContext, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
    shortcutManager.requestPinShortcut(info, shortcutCallbackIntent.getIntentSender());
  }
} else {
  ToastShow.show("设备不支持在桌面创建快捷图标!");
}
复制代码
  • 此时 Android 就实现了添加桌面快捷方式,但 iOS 可不像 Android 这么直接,iOS 需要一个中间过渡页面,在中间过渡页面通过和 iOS 协商的协议最终跳转到目标页面

  • Web 中间过渡页面代码

<!DOCTYPE html>
<html>
  <head>
    <title>demo</title>

    // 设置 iOS 设备添加到桌面打开时全屏,对应着 h5 在 window 中的 window.navigator.standalone 属性
    <meta content="yes" name="apple-touch-fullscreen" />
    <meta content="yes" name="apple-mobile-web-app-capable" />

    // 设置 iOS 设备添加到桌面的标题
    <meta name="apple-mobile-web-app-title" content="瓜分十万现金" />

    // 设置 iOS 设备添加到桌面的图标
    <link
      id="J_desktopIcon"
      sizes="114x114"
      rel="apple-touch-icon-precomposed"
      href="https://xxx/SysActivity/1438082076824965120.png"
    />
  </head>

  <body>
    <a id="links" href="#" style="display: none" />

    <script>
      if (window.navigator.standalone) {
        let obj = document.getElementById('links')

        // 当判断 window 有 standalone 属性的时候,此处填写和原生工程师约定的 app 协议地址,由 iOS 决定跳转到最终目标页面
        obj.href = `iOS 协商的协议`
        obj.click()
      }
    </script>
  </body>
</html>
复制代码
  • iOS 代码
    • 苹果用的是 WKWebView
- (void) userContentController:(WKUserContentController *) userContentController didReceiveScriptMessage:(WKScriptMessage *) message {

  // 此处 xxx 是跳转到上述 web h5 的中间过渡页面地址,并不是最终目标页地址
  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url[@"xxx"]] options:@{} completionHandler:^(BOOL success) {}];
}
复制代码

效果图

  • Android 效果图

Android 效果图

  • iOS 效果图(gif 限制大小,会模糊一点)

iOS 效果图

猜你喜欢

转载自juejin.im/post/7016562241600225311