JetPack學(xué)習(xí)筆記之Navigation(三)
Navigation組件還提供了一個很實用的特性DeepLink,即深層鏈接。通過該特性,可以利用PendingIntent或一個真實的URL鏈接,直接跳轉(zhuǎn)到應(yīng)用程序中的某個頁面(Activity或者Fragment)。
分別對應(yīng)兩種應(yīng)用場景:
PendingIntent的方式。當應(yīng)用程序接收到某個通知推送,你希望用戶點擊該通知后,能夠直接跳轉(zhuǎn)到APP內(nèi)的某個頁面,那么可以通過PendingIntent的方式實現(xiàn)。
URL的方式,當用戶通過手機瀏覽器瀏覽網(wǎng)站上的某個頁面時,可以在網(wǎng)上上放置一個類似于”在應(yīng)用內(nèi)打開“的按鈕。如果用戶安裝了我們的APP,可以直接跳轉(zhuǎn)到應(yīng)用程序,如果沒有安裝,可以跳轉(zhuǎn)到應(yīng)用商店內(nèi)對應(yīng)的APP的下載頁面,從而引導(dǎo)用戶安裝。
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("這是通知內(nèi)容")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(getPendingIntent())
.setAutoCancel(true);
?
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(getActivity());
notificationManagerCompat.notify(1,builder.build());
}
1.2 構(gòu)建PendingIntent對象,在其中設(shè)置當通知被點擊時需要跳轉(zhuǎn)到的目的地以及傳遞的參數(shù)。
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 在導(dǎo)航圖中為頁面添加<deepLink>標簽。app:uri屬性中對應(yīng)的是WEB頁面地址,后面的參數(shù)會通過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設(shè)置<nav-graph>標簽,當用戶在瀏覽器中訪問你的網(wǎng)址時,APP可以得到監(jiān)聽。
<activity android:name=".navigation.NavigationActivity">
<nav-graph android:value="@navigation/nav_graph"/>
</activity>
2.3 測試。

image.png