如何使(NotificationCompat.Builder)在API级别28上工作?

时间:2019-12-01 09:55:21

标签: android android-studio

[由于版本问题,此对象未实现

NotificationCompat.Builder builder = new NotificationCompat.Builder (context)

如何在android studio中解决它? ]

我的代码: 在家庭活动中

''' 公共无效警报(){

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 10);
    calendar.set(Calendar.MINUTE, 16);
    calendar.set(Calendar.SECOND, 0);

    Intent alertIntent = new Intent(getApplicationContext(), AlertReceiver.class);
    AlarmManager alarmManager = (AlarmManager) getSystemService( ALARM_SERVICE );

    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), PendingIntent.getBroadcast(getApplicationContext(), 0, alertIntent,
            PendingIntent.FLAG_UPDATE_CURRENT ));

}

'''

public class AlertReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        PendingIntent notification = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);


        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.ic_notifications_active_black_24dp)
                .setContentTitle("CURA here\n")
                .setContentText("Do you feel good :), if not :(, I can help you ^_^");

        builder.setContentIntent(notification);
        builder.setDefaults(NotificationCompat.DEFAULT_SOUND);
        builder.setAutoCancel(true);

        NotificationManager mm =( NotificationManager ) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mm.cancel(1);
        mm.notify(1, builder.build());

    }


}

用于说明problem

的图片附件

1 个答案:

答案 0 :(得分:0)

您必须使用NotificationChannel才能在android 28中使用通知

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(NOTIFICATION_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);
    }
}

在此处检查official documentation

然后您可以按以下方式使用:

NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)