Android 7.1 и более низкие двойные уведомления, показывающие - PullRequest
0 голосов
/ 23 февраля 2020

Я добавил запланированные уведомления в свое приложение, и все работает хорошо, за исключением android версии менее 7.1, где отображаются двойные уведомления.

Вот мой класс издателя уведомлений (BroadcastReciever)

public class NotificationPublisher extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    this.context = context;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        createChannels();
    }

    sendNotification("title", "body", notificationId, activity);
}

@RequiresApi(api = Build.VERSION_CODES.O)
private void createChannels() {
    NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
    channel.enableLights(true);
    channel.enableVibration(true);
    channel.setDescription(CHANNEL_DESCRIPTION);
    channel.setLightColor(Color.RED);
    channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);

    NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    manager.createNotificationChannel(channel);
}

public void sendNotification(String title, String body, int id, Class activity) {
    Intent intents = new Intent(context, activity);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, id, intents, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification notification = new NotificationCompat.Builder(context, CHANNEL_ID)
            .setContentTitle(title)
            .setContentText(body)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setStyle(new NotificationCompat.BigTextStyle().setBigContentTitle(title).bigText(body))
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .build();

    NotificationManagerCompat.from(context).notify(new Random().nextInt(), notification);
}

}

Вот мой код для планирования уведомления:

public static void createNotification(Context context) {
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent("app.action.DISPLAY_NOTIFICATION");
    intent.putExtra("notificationId", notificationID);

    Calendar calReminder = Calendar.getInstance();
    calReminder.setTimeInMillis(System.currentTimeMillis());
    calReminder.set(Calendar.HOUR_OF_DAY, 16);
    calReminder.set(Calendar.MINUTE, 30);

    PendingIntent broadcast = PendingIntent.getBroadcast(context, notificationID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calReminder.getTimeInMillis(), AlarmManager.INTERVAL_DAY, broadcast);
}

Вот мой код MainActivity при запуске приложения:

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

private NotificationPublisher broadcastReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    broadcastReceiver = new NotificationPublisher();

    setNotificationScheduler(this);
}

public static void setNotificationScheduler(Context context) {
    AppNotifications.createNotification(context);
}

@Override
protected void onStart() {
    super.onStart();
    IntentFilter intentFilter = new IntentFilter("app.action.DISPLAY_NOTIFICATION");
    intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
    registerReceiver(broadcastReceiver, intentFilter);
}

}

Я не могу найти, почему он отображает двойные уведомления на android 7.1 и ниже.

Также просто для того, чтобы убедиться: неправильно создавать уведомления при запуске? Есть ли еще какой-нибудь способ сделать это по книгам?

Заранее спасибо.

1 Ответ

1 голос
/ 23 февраля 2020
 NotificationManagerCompat notificationManager = NotificationManagerCompat.from(app);
    notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());

Добавьте этот код в класс издателей уведомлений.

...