Android 8.0實現傳送通知
阿新 • • 發佈:2020-07-30
在Android8.0以後,針對Notification 通知api做了修改,新增了通知渠道(NotificationCannel)。下面就把demo的詳細程式碼記錄下:
1.Application 為NotificationManager新增通知頻道
import android.app.Application; import com.xinrui.ndkapp.notification.NotificationChannels; public class NdkApplication extends Application { @Override public void onCreate() { super.onCreate(); NotificationChannels.createAllNotificationChannels(this); } }
2.NotificationChannels 類
public class NotificationChannels { public final static String CRITICAL = "critical"; public final static String IMPORTANCE = "importance"; public final static String DEFAULT = "default"; public final static String LOW = "low"; public final static String MEDIA = "media"; public static void createAllNotificationChannels(Context context) { NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if(nm == null) { return; } NotificationChannel mediaChannel = new NotificationChannel( MEDIA,context.getString(R.string.app_name),NotificationManager.IMPORTANCE_DEFAULT); mediaChannel.setSound(null,null); mediaChannel.setVibrationPattern(null); nm.createNotificationChannels(Arrays.asList( new NotificationChannel( CRITICAL,NotificationManager.IMPORTANCE_HIGH),new NotificationChannel( IMPORTANCE,NotificationManager.IMPORTANCE_DEFAULT),new NotificationChannel( DEFAULT,NotificationManager.IMPORTANCE_LOW),new NotificationChannel( LOW,NotificationManager.IMPORTANCE_MIN),//custom notification channel mediaChannel )); } }
3.傳送通知
public void sendSimpleNotification(Context context,NotificationManager nm) { //建立點選通知時傳送的廣播 Intent intent = new Intent(context,NotificationMonitorService.class); intent.setAction("android.service.notification.NotificationListenerService"); PendingIntent pi = PendingIntent.getService(context,intent,0); //建立刪除通知時傳送的廣播 Intent deleteIntent = new Intent(context,NotificationMonitorService.class); deleteIntent.setAction(Intent.ACTION_DELETE); PendingIntent deletePendingIntent = PendingIntent.getService(context,deleteIntent,0); //建立通知 Notification.Builder nb = new Notification.Builder(context,NotificationChannels.DEFAULT) //設定通知左側的小圖示 .setSmallIcon(R.drawable.ic_notification) //設定通知標題 .setContentTitle("Simple notification") //設定通知內容 .setContentText("Demo for simple notification!") //設定點選通知後自動刪除通知 .setAutoCancel(true) //設定顯示通知時間 .setShowWhen(true) //設定通知右側的大圖示 .setLargeIcon(BitmapFactory.decodeResource(context.getResources(),R.drawable.ic_notifiation_big)) //設定點選通知時的響應事件 .setContentIntent(pi) //設定刪除通知時的響應事件 .setDeleteIntent(deletePendingIntent); //傳送通知 nm.notify(Notificaitons.NOTIFICATION_SAMPLE,nb.build()); }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。