Android O - Notification Channels and NotificationCompat

前端 未结 6 1355
忘了有多久
忘了有多久 2021-02-05 03:57

I cannot change this feeling: again, the Android developers came up with something new and leave everybody in the dark about how they would think the feature is used.

I

6条回答
  •  情歌与酒
    2021-02-05 04:09

    This is my solution to generate notifications on Android O and maintain backward compatibility:

            String idChannel = "my_channel_01";
            Intent mainIntent;
    
            mainIntent = new Intent(context, LauncherActivity.class);
    
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, mainIntent, 0);
    
            NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    
            NotificationChannel mChannel = null;
            // The id of the channel.
    
            int importance = NotificationManager.IMPORTANCE_HIGH;
    
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context, null);
            builder.setContentTitle(context.getString(R.string.app_name))
                    .setSmallIcon(getNotificationIcon())
                    .setContentIntent(pendingIntent)
                    .setContentText(context.getString(R.string.alarm_notification) + ManagementDate.getIstance().hourFormat.format(getAlarm(context, 0)));
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                mChannel = new NotificationChannel(idChannel, context.getString(R.string.app_name), importance);
                // Configure the notification channel.
                mChannel.setDescription(context.getString(R.string.alarm_notification));
                mChannel.enableLights(true);
                mChannel.setLightColor(Color.RED);
                mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                mNotificationManager.createNotificationChannel(mChannel);
            } else {
                builder.setContentTitle(context.getString(R.string.app_name))
                        .setPriority(NotificationCompat.PRIORITY_HIGH)
                        .setColor(ContextCompat.getColor(context, R.color.transparent))
                        .setVibrate(new long[]{100, 250})
                        .setLights(Color.YELLOW, 500, 5000)
                        .setAutoCancel(true);
            }
            mNotificationManager.notify(1, builder.build());
    

提交回复
热议问题