Android收藏集

JetPack学习笔记之Navigation(三)

2020-08-06  本文已影响0人  秀儿2020

JetPack学习笔记之Navigation(三)

Navigation组件还提供了一个很实用的特性DeepLink,即深层链接。通过该特性,可以利用PendingIntent或一个真实的URL链接,直接跳转到应用程序中的某个页面(Activity或者Fragment)。

分别对应两种应用场景:

1、PendingIntent的方式
1.1 模拟用户收到一条推送消息
 private void sendNotification(){
 if(getActivity() == null){
 return;
 }
 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
 int importance = NotificationManager.IMPORTANCE_DEFAULT;
 NotificationChannel channel = new NotificationChannel("channel_id","channelName",importance);
 channel.setDescription("description");
 NotificationManager notificationManager = getActivity().getSystemService(NotificationManager.class);
 notificationManager.createNotificationChannel(channel);
 }
 NotificationCompat.Builder builder = new NotificationCompat
 .Builder(getActivity(),"channel_id")
 .setSmallIcon(R.mipmap.ic_launcher)
 .setContentTitle("这是通知标题")
 .setContentText("这是通知内容")
 .setPriority(NotificationCompat.PRIORITY_DEFAULT)
 .setContentIntent(getPendingIntent())
 .setAutoCancel(true);
​
 NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(getActivity());
 notificationManagerCompat.notify(1,builder.build());
 }
1.2 构建PendingIntent对象,在其中设置当通知被点击时需要跳转到的目的地以及传递的参数。
private PendingIntent getPendingIntent(){
 if(getActivity() != null){
 Bundle bundle = new Bundle();
 bundle.putString("params","this is the params");
 return Navigation.findNavController(getActivity(),R.id.jumpBtn)
 .createDeepLink()
 .setGraph(R.navigation.nav_graph)
 .setDestination(R.id.secondFragment)
 .setArguments(bundle)
 .createPendingIntent();
 }
 return null;
 }
2、URL的方式
2.1 在导航图中为页面添加<deepLink>标签。app:uri属性中对应的是WEB页面地址,后面的参数会通过Bundle对象传递到页面中。
 <fragment
 android:id="@+id/secondFragment"
 android:name="com.example.jetpackpro.navigation.SecondFragment"
 android:label="fragment_second"
 tools:layout="@layout/fragment_second" >
​
 <deepLink app:uri="www.baidu.com/{params}"/>
​
 </fragment>
2.2 为Activity设置<nav-graph>标签,当用户在浏览器中访问你的网址时,APP可以得到监听。
 <activity android:name=".navigation.NavigationActivity">
 <nav-graph android:value="@navigation/nav_graph"/>
 </activity>
2.3 测试。
image.png
总结

Navigation组件为页面切换和APP Bar 的变化提供了统一的解决方案,配合Android Studio,我们可以通过图形化的方式管理配置页面切换,甚至加入动画效果。页面切换通常还会伴随着参数的传递,Android Studio为我们提供了safe args插件,通过该插件,我们可以以更安全的方式在页面间传递参数,对于APP Bar中的菜单,JetPack为我们提供了NavigationUI组件,该组件使APP Bar中的菜单能够与页面切换对应起来,最后,还提供了DeepLink,通过DeepLink,我们可以使用PendingIntent或URL的方式跳转到应用中的某个特定的页面。

上一篇 下一篇

猜你喜欢

热点阅读