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

问题描述 投票:-1回答:1

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

[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的图像附件

android android-studio
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.