- 本博客例子来自-Project-FoodList
Android 8.0 新特性
- Android 8.0 新特性
- NotificationChannel是android8.0新增的特性,如果App的targetSDKVersion >= 26,没有设置channel通知渠道的话,就会导致通知无法展示。
- NotificationChannel 官方示例
private void createNotificationChannel() { // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = getString(R.string.channel_name); String description = getString(R.string.channel_description); int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); channel.setDescription(description); // Register the channel with the system; you can't change the importance // or other notification behaviors after this NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } }
Example
-
创建
Notification
代码private void createNotification(Context context, Collection item) { Intent myIntent = new Intent(context, DetailActivity.class); // 实例化一个Bundle Bundle myBundle = new Bundle(); // 把item数据放入到bundle中 myBundle.putSerializable("item", item); //把bundle放入intent里 myIntent.putExtra("Message", myBundle); PendingIntent myPendingIntent = PendingIntent.getActivity(context, 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT); String id = "channel_id_0"; String name="channel_name_0"; //获取状态通知栏管理 NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notify = null; // SDK >= 26 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH); mChannel.enableVibration(true); mChannel.setVibrationPattern(new long[]{0,100,0}); // 震动 manager.createNotificationChannel(mChannel); NotificationCompat.Builder builder = new NotificationCompat.Builder(context); //对Builder进行配置,此处仅选取了几个 builder.setContentTitle("今日推荐") //设置通知栏标题 .setChannelId(id) .setContentText(item.getFoodName()) //设置通知栏显示内容 .setSmallIcon(R.mipmap.empty_star) //设置通知小ICON(通知栏),可以用以前的素材,例如空星 .setWhen(System.currentTimeMillis()) .setShowWhen(true) .setContentIntent(myPendingIntent); notify = builder.build(); } else { // SDK <= 26 Notification.Builder builder = new Notification.Builder(context); //对Builder进行配置,此处仅选取了几个 builder.setContentTitle("今日推荐") //设置通知栏标题 .setContentText(item.getFoodName()) //设置通知栏显示内容 .setSmallIcon(R.mipmap.empty_star) //设置通知小ICON(通知栏),可以用以前的素材,例如空星 .setContentIntent(myPendingIntent); //builder.setVibrate(new long[]{100,50,100}); // 设置震动 notify = builder.build(); } notify.flags = Notification.FLAG_AUTO_CANCEL; // 点击一次后消失 manager.notify(0, notify); }
-
效果展示