Уведомление службы Android переднего плана не отображается в строке состояния - PullRequest
0 голосов
/ 09 июля 2019

Я попробовал различные решения здесь на SO и, похоже, не смог заставить ни одного из них работать. Уведомление просто не будет отображаться. Кто-нибудь может указать, где могут быть возможные проблемы в моем коде?

private void startRunningInForeground() {

        setupNotificationChannel();

        Intent showTaskIntent = new Intent(getApplicationContext(), MainActivity.class);
        showTaskIntent.setAction(Intent.ACTION_MAIN);
        showTaskIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        showTaskIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent contentIntent = PendingIntent.getActivity(
                getApplicationContext(),
                0,
                showTaskIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, SERVICE_NOTIFICATION_CHANNEL);
        builder.setSmallIcon(R.drawable.ic_stat_ic_logo);
        builder.setContentTitle(getString(R.string.merge_notif_title));
        builder.setContentText(getString(R.string.merge_notif_description));
        builder.setContentIntent(contentIntent);
        builder.setWhen(System.currentTimeMillis());
        builder.setAutoCancel(false);
        builder.setOngoing(true);

        startForeground(NOTIFICATION_ID, builder.build());
    }

    private void setupNotificationChannel() {
        // Only run this on versions of Android that require notification channels.
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            return;
        }

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if(notificationManager == null) {
            return;
        }

        NotificationChannel cachingChannel = new NotificationChannel(SERVICE_NOTIFICATION_CHANNEL,
                getString(R.string.merge_channel), NotificationManager.IMPORTANCE_HIGH);
        cachingChannel.setDescription(getString(R.string.merge_channel_description));
        cachingChannel.enableLights(false);
        cachingChannel.enableVibration(false);

        notificationManager.createNotificationChannel(cachingChannel);
    }  

Не получено никаких сообщений об ошибках, и канал уведомлений создается, потому что я вижу его в настройках приложения.

Ответы [ 2 ]

0 голосов
/ 09 июля 2019

Так что я смог заставить его работать, расширив Service вместо IntentService.Я не могу объяснить, почему это сработало, но теперь все работает, как и ожидалось.

0 голосов
/ 09 июля 2019

Что делает ваш startForeground?

Попробуйте изменить это и убедитесь, что ваша ОС> Android 8.0

Кстати, канал нужно создать только один раз.

PendingIntent contentIntent = PendingIntent.getActivity(
            getApplicationContext(),
            NOTIFICATION_ID, <---
            showTaskIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);


startForeground(NOTIFICATION_ID, builder.build());
notificationManager.notify(NOTIFICATION_ID, builder.build()); <--

Возможно из-за ограничений службы Android O bg

//Start service:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  startForegroundService(new Intent(this, YourService.class));
} else {
  startService(new Intent(this, YourService.class));
}
...