在使用Navigation组件的时候,我们肯定会接触到Navigation的DeepLink,中文名称是深层链接。这篇文章分享一下DeepLink的知识,希望对看文章的小伙伴有所启发。
DeepLink的应用场景
PendingIntent,这种方式是在App接收到某个通知推送,我们希望用户在单击这个通知,就可以直接跳转到展示通知内容的界面。
URL,当用户通过手机浏览器网站上的某个界面的时候,可以在网页上一个类似于“在应用内打开”的按钮。如果用户的手机有安装的应用程序,我们就可以DeepLink就可以打开相应的界面。如果没有安装的情况下,就可以跳转App的下载界面,引导用户安装应用程序。
PendingIntent的使用
场景:设想在通知栏的一条通知,点击跳转展示通知详情。
private fun sendNotification(){
val builder:NotificationCompat.Builder = NotificationCompat.Builder(this,"CHANNEL_ID")
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle("DeepLinkDemo")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(getPendingIntent())
.setAutoCancel(true)
}
private fun getPendingIntent(): PendingIntent {
val bundle = Bundle()
bundle.putString("params","PendingIntent")
return Navigation.findNavController(this,R.id.sendNotification)
.createDeepLink()
.setGraph(R.navigation.nav_graph)
.setDestination(R.id.mainFragment)
.setArguments(bundle)
.createPendingIntent()
}
上面的代码就是给通知设置PendingIntent,然后我们在PendingIntent里面设置好目的地。如果要自己设置状态栏通知,可以尝试这种写法。
URL的使用
1.在导航图中页面中<deepLink/>,在app:uri里面填入你相应的Web页面地址,参数可以通过Bundle对象传进去,代码示例:
<deepLink app:uri="www.xxx.com/{params}"/>
2.给Activity设置<nav-graph/>标签。代码示例:
<activity android:name=".DeepLinkActivity">
<nav-graph android:value="@navigation/graph_deep_link"/>