其他
使用深层链接导航 | MAD Skills
今天为大家发布本系列文章中的第四篇: 使用深层链接 (Deep Links) 导航。如果您想回顾过去发布的内容,请参考下面链接查看:
介绍
深层链接
https://developer.android.google.cn/guide/navigation/navigation-deep-link
完整代码
https://github.com/android/architecture-components-samples/tree/main/MADSkillsNavigationSample
甜甜圈深层链接
创建隐式深层链接
<activity
android:name="com.android.samples.donuttracker.MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<nav-graph android:value="@navigation/nav_graph" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="android.app.shortcuts"
android:resource="@xml/shortcuts" />
</activity>
<shortcuts
xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
android:shortcutId="NewDonutDialogFragment"
android:enabled="true"
android:shortcutShortLabel="@string/static_shortcut_label_short"
android:shortcutLongLabel="@string/static_shortcut_label_long"
android:shortcutDisabledMessage=
"@string/static_shortcut_disabled_message"
android:icon="@drawable/donut_with_sprinkles">
<intent
android:action="android.intent.action.VIEW"
android:data="myapp://navdonutcreator.com/donutcreator" />
</shortcut>
</shortcuts>
创建显式深层链接
binding.doneButton.setOnClickListener {
// 先获取上下文参数,因为 Fragment 可能在下面的 lambda 调用前就消失了
val context = requireContext().applicationContext
val navController = findNavController()
donutEntryViewModel.addData(
donut?.id ?: 0,
binding.name.text.toString(),
binding.description.text.toString(),
binding.ratingBar.rating.toInt()
) { actualId ->
val arg = DonutEntryDialogFragmentArgs(actualId).toBundle()
val pendingIntent = navController
.createDeepLink()
.setDestination(R.id.*donutEntryDialogFragment*)
.setArguments(arg)
.createPendingIntent()
Notifier.postNotification(actualId, context, pendingIntent)
}
dismiss()
}
fun postNotification(id: Long,
context: Context,
intent: PendingIntent) {
val builder = NotificationCompat.Builder(context, channelId)
builder.setContentTitle(context
.getString(R.string.deepLinkNotificationTitle))
.setSmallIcon(R.drawable.donut_with_sprinkles)
val text = context.getString(R.string.addDonutInfo)
val notification = builder.setContentText(text)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(intent)
.setAutoCancel(true)
.build()
val notificationManager =
NotificationManagerCompat.from(context)
notificationManager.cancelAll()
notificationManager.notify(id.toInt(), notification)
}
总结
更多信息
https://github.com/android/architecture-components-samples/tree/main/MADSkillsNavigationSample
当您在文章末尾看到 "粉丝回馈活动" 的标识 (如上图所示),请在公众号主页通过私信发送您对 "Android 开发者" 公众号的意见、建议、想法和期待。
推荐阅读