【问题标题】:Nav Deep Link from a foreground service来自前台服务的导航深度链接
【发布时间】:2020-09-23 09:10:18
【问题描述】:

我正在尝试从前台服务通知导航到导航图中的片段。我使用下面的代码创建了一个没有按预期工作的显式深层链接。

val pendingIntent = NavDeepLinkBuilder(this) // this is the Service context!
            .setComponentName(MainActivity::class.java)
            .setGraph(R.navigation.primary_app_nav)
            .setDestination(R.id.shareSheetFragment)
            .setArguments(bundle)
            .createPendingIntent()

阅读guide 后,我知道您需要使用活动上下文而不是任何其他上下文(在我的情况下是服务上下文)。

请注意,如果提供的上下文不是 Activity,则构造函数 使用 PackageManager.getLaunchIntentForPackage() 作为默认值 要启动的活动(如果有)。

我的问题是如何从前台服务中获取 MainActivity 上下文?

【问题讨论】:

    标签: android android-service android-notifications


    【解决方案1】:

    我还没有找到使用显式深层链接的方法,但我选择了一种利用隐式深层链接的解决方案。

    首先,在导航图 XML 中添加指向您的片段的深层链接。

    <deepLink android:id="@+id/deepLink"
       app:uri="my-app://com.example.app/hotspot?ssid={ssid}&amp;passkey={passkey}" />
    

    在清单中的&lt;activity /&gt; 中添加&lt;nav-graph /&gt; 标记。这将确保创建所有意图过滤器并将其合并到您的清单中。

    <nav-graph android:value="@navigation/primary_app_nav" />
    

    为通知创建您的PendingIntent,如下所示。

    fun getNotificationPendingIntent(ssid: String, passkey: String): PendingIntent {
         val uri = Uri.parse("my-app://com.example.app/hotspot?ssid=$ssid&passkey=$passkey")
         val bundle = Bundle().apply { putParcelable(SHARE_DEEP_LINK_KEY, uri) }
         val intent = Intent(this, SailsActivity::class.java).apply {
              putExtras(bundle)
              // to clear the back stack
              addFlags(FLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_SINGLE_TOP
                         or FLAG_ACTIVITY_CLEAR_TASK or FLAG_ACTIVITY_NEW_TASK)
         }
         return PendingIntent.getActivity(this, launchShareSheetCode, intent, PendingIntent.FLAG_UPDATE_CURRENT)
    }
    

    最后,您需要处理来自Activity 类的onCreate() 方法的深层链接意图。

    private fun handleDeepLinkIntent() {
        val deepLink = intent.extras?.getParcelable(SHARE_DEEP_LINK_KEY) as? Uri
        deepLink?.also {
            val intent = Intent(this, SenderService::class.java)
            this.bindService(intent, serviceConn, Context.BIND_ABOVE_CLIENT)
            navigateDeepLink(it)
        }
    }
    
    private fun navigateDeepLink(uri: Uri) {
        findNavController(R.id.navHostFragment).apply {
            if (graph.hasDeepLink(uri)) 
                navigate(uri)
            else {
                currentDestination?.getAction(id)?.let {
                    navigate(id)
                }
            }
        }
    }
    

    深层链接 URI 参数在目标片段中自动可供您使用。

    if (arguments != null) {
         val ssid = requireArguments().getString("ssid")
         val passkey = requireArguments().getString("passkey")
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-18
      • 2019-09-26
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多