Android 8.0通知欄推送及適配
阿新 • • 發佈:2018-11-14
上一篇我們確保了我們開啟了通知欄的許可權,那麼接下來就是傳送推送了,廢話不多說,上程式碼。
首先我們判斷手機版本號,Android版本大於8.0的時候呢,我們需要進行一下通道的操作才可:判斷版本號程式碼接好
//此處判斷安卓版本號是否大於或者等於Android8.0 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { String channelId = "chat";//設定通道的唯一ID String channelName = "聊天訊息";//設定通道名 int importance = NotificationManager.IMPORTANCE_HIGH;//設定通道優先順序 createNotificationChannel(channelId, channelName, importance,title,text); } else { sendSubscribeMsg(title,text); }
Android8.0+適配
@TargetApi(Build.VERSION_CODES.O) private void createNotificationChannel(String channelId, String channelName, int importance,String title,String text) { NotificationChannel channel = new NotificationChannel(channelId, channelName, importance); NotificationManager notificationManager = (NotificationManager) AppApplication.getContext().getSystemService(NOTIFICATION_SERVICE); notificationManager.createNotificationChannel(channel); sendSubscribeMsg(title,text); }
通知欄推送程式碼
public void sendSubscribeMsg(String title,String text) { NotificationManager manager = (NotificationManager) AppApplication.getContext().getSystemService(NOTIFICATION_SERVICE); Notification notification = new NotificationCompat.Builder(AppApplication.getContext(), "chat") .setContentTitle(title) .setContentText(text) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.mipmap.logo) .setLargeIcon(BitmapFactory.decodeResource(AppApplication.getContext().getResources(), R.mipmap.logo)) .setAutoCancel(true) .build(); manager.notify(2, notification); }
我們還可以給notification設定其他屬性,例如:
setCustomContentView(createContentView()) 用於設定自定義的View
notification.flags |= Notification.FLAG_NO_CLEAR; 設定flags 使其無法被滑動刪除