Android версии 8.1 не отображает уведомление о строке состояния [дубликат]

Хороший вопрос!

После нескольких (жестких) дебатов с моими товарищами по команде + мой опыт работы с приложениями MVC я бы не рекомендовал передавать viewmodel на ваш уровень сервиса / домена.

  1. ViewModel принадлежит к презентации, независимо от того, что.
  2. Поскольку viewModel может быть комбинацией разных моделей (например: 1 viewModel, построенный из 10 моделей), ваш уровень обслуживания должен работать только с вашими объектами домена.

В противном случае ваш сервисный уровень окажется непригодным для использования, потому что ограничено вашими viewModels, которые являются специфическими для одного вида.

Хорошие инструменты, такие как https: / /github.com/AutoMapper/AutoMapper, чтобы выполнить задание сопоставления.

121
задан Vadim Kotov 3 May 2018 в 10:09
поделиться

9 ответов

В Android O необходимо использовать канал с вашим Notification Builder

ниже, это пример кода:

// Sets an ID for the notification, so it can be updated.
int notifyID = 1; 
String CHANNEL_ID = "my_channel_01";// The id of the channel. 
CharSequence name = getString(R.string.channel_name);// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(MainActivity.this)
            .setContentTitle("New Message")
            .setContentText("You've received new messages.")
            .setSmallIcon(R.drawable.ic_notify_status)
            .setChannelId(CHANNEL_ID)
            .build();

Или с использованием совместимости по:

NotificationCompat notification =
        new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setChannelId(CHANNEL_ID).build();



NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
 mNotificationManager.createNotificationChannel(mChannel);

// Issue the notification.
mNotificationManager.notify(notifyID , notification);

или если вы хотите просто исправить, используйте следующий код:

NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
       mNotificationManager.createNotificationChannel(mChannel);
    }

Обновления: Ссылка NotificationCompat.Builder

NotificationCompat.Builder(Context context)

Этот конструктор устарел на уровне API 26.0.0, поэтому вы должны использовать

Builder(Context context, String channelId)

, поэтому нет необходимости в setChannelId с новым конструктором.

И вы должны использовать последняя из библиотеки AppCompat в настоящее время 26.0.2

compile "com.android.support:appcompat-v7:26.0.+"

Источник из Канал разработчиков Android на Youtube

Кроме того, вы можете проверить официальные Android-документы

171
ответ дан amorenew 15 August 2018 в 17:47
поделиться
  • 1
    Вы также должны создать канал, прежде чем его можно будет использовать. См. developer.android.com/reference/android/app/… – Guillaume Perrot 14 June 2017 в 02:35
  • 2
    setChannel устарел в пользу setChannelId – Guillaume Perrot 14 June 2017 в 02:42
  • 3
    Нет, вы получите сообщение об ошибке, если вы не создадите канал хотя бы один раз в жизни приложения. – Guillaume Perrot 14 June 2017 в 18:33
  • 4
    @amorenew, видимо, у меня было неправильное название канала. Теперь работает. Спасибо, но ваш ответ не завершен ... вы должны сначала создать канал, используя mNotificationManager.createNotificationChannel (mChannel); (Я сделал это в своем классе приложения) ... см. Google docs для этого. Возможно, добавьте это в свой ответ. – JPM 13 September 2017 в 16:28
  • 5
    Какие зависимости / версии следует настраивать для создания нового конструктора NotificationCompat.Builder(Context, String)? Я использую (между прочим): - compileSdkVersion 26 - buildToolsVersion '26.0.2' - compile 'com.android.support:appcompat-v7:26.0.0-beta2', и все же он все еще не принимает мой конструктор, используя Context и String. Есть идеи? – Loisaida Sam 12 October 2017 в 03:35

Здесь я размещаю некоторую функцию быстрого решения с обработкой намерений

public void showNotification(Context context, String title, String body, Intent intent) {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    int notificationId = 1;
    String channelId = "channel-01";
    String channelName = "Channel Name";
    int importance = NotificationManager.IMPORTANCE_HIGH;

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannel mChannel = new NotificationChannel(
                channelId, channelName, importance);
        notificationManager.createNotificationChannel(mChannel);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(title)
            .setContentText(body);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addNextIntent(intent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
            0,
            PendingIntent.FLAG_UPDATE_CURRENT
    );
    mBuilder.setContentIntent(resultPendingIntent);

    notificationManager.notify(notificationId, mBuilder.build());
}
21
ответ дан FinalDark 15 August 2018 в 17:47
поделиться

В дополнение к этому ответу вам нужно создать канал уведомления, прежде чем он сможет быть использован.

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

      /* Create or update. */
      NotificationChannel channel = new NotificationChannel("my_channel_01",
          "Channel human readable title", 
          NotificationManager.IMPORTANCE_DEFAULT);
      mNotificationManager.createNotificationChannel(channel);
  }

Также вам нужно использовать каналы только в том случае, если ваша targetSdkVersion 26 или выше.

Если вы используете NotificationCompat.Builder, вам также необходимо обновить бета-версию библиотеки поддержки: https://developer.android.com/topic/libraries/ support-library / revisions.html # 26-0-0-beta2 (чтобы иметь возможность вызвать setChannelId в компоновщике сопоставления.)

Будьте осторожны, так как это обновление библиотеки повышает minSdkLevel до 14.

59
ответ дан Guillaume Perrot 15 August 2018 в 17:47
поделиться
  • 1
    Это повысит предупреждение, если min api будет ниже 26. Добавьте @TargetApi (26) непосредственно перед созданием канала для подавления предупреждения. – s-hunter 27 April 2018 в 02:03
  • 2
    Если у вас есть пример, похожий на образец кода, это не приведет к предупреждению, быстрое исправление имеет разные предложения, один из которых должен окружить код, если проверка версии. Если вы настроите проверку версии if, Android Studio может запутаться и, возможно, ее не обнаружит. – Guillaume Perrot 14 June 2018 в 00:54

Для тех, кто борется с этим, попробовав вышеуказанные решения, убедитесь, что идентификатор канала, используемый при создании канала уведомлений, идентичен идентификатору канала, установленному в конструкторе уведомлений.

const val CHANNEL_ID = "EXAMPLE_CHANNEL_ID"

// create notification channel
val notificationChannel = NotificationChannel(CHANNEL_ID, 
NOTIFICATION_NAME, NotificationManager.IMPORTANCE_HIGH)

// building notification
NotificationCompat.Builder(context)
                    .setSmallIcon(android.R.drawable.ic_input_add)
                    .setContentTitle("Title")
                    .setContentText("Subtitle")   
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setChannelId(CHANNEL_ID)
0
ответ дан Jules 15 August 2018 в 17:47
поделиться

Это ошибка в firebase api версии 11.8.0. Поэтому, если вы уменьшите версию API, вы не столкнетесь с этой проблемой.

2
ответ дан M.Noman 15 August 2018 в 17:47
поделиться
  • 1
    Вы можете указать ссылку на эту информацию? – deadfish 19 March 2018 в 12:28
  • 2
    На самом деле я проверил его. Если вы работаете над эмулятором Android - проверьте свое приложение на физическом устройстве. Новые эмуляторы каким-то образом не отображают уведомления. – deadfish 19 March 2018 в 14:16
  • 3
    Нет, на самом деле это на самом деле ошибка в firebase версии 11.8.0, и теперь она исправлена ​​в более новой версии 12.0.0. Для справки вы можете увидеть официальные примечания к выпуску: firebase.google.com/support/release-notes/android – M.Noman 22 March 2018 в 18:38
  • 4
    Спасибо, это хорошо знать. – deadfish 23 March 2018 в 13:35
public class MyFirebaseMessagingServices extends FirebaseMessagingService {
    private NotificationChannel mChannel;
    private NotificationManager notifManager;
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getData().size() > 0) {
            try {
                JSONObject jsonObject = new JSONObject(remoteMessage.getData());
                displayCustomNotificationForOrders(jsonObject.getString("title"), jsonObject.getString("description"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void displayCustomNotificationForOrders(String title, String description) {
        if (notifManager == null) {
            notifManager = (NotificationManager) getSystemService
                    (Context.NOTIFICATION_SERVICE);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationCompat.Builder builder;
            Intent intent = new Intent(this, Dashboard.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent;
            int importance = NotificationManager.IMPORTANCE_HIGH;
            if (mChannel == null) {
                mChannel = new NotificationChannel
                        ("0", title, importance);
                mChannel.setDescription(description);
                mChannel.enableVibration(true);
                notifManager.createNotificationChannel(mChannel);
            }
            builder = new NotificationCompat.Builder(this, "0");

            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                    Intent.FLAG_ACTIVITY_SINGLE_TOP);
            pendingIntent = PendingIntent.getActivity(this, 1251, intent, PendingIntent.FLAG_ONE_SHOT);
            builder.setContentTitle(title)  
                    .setSmallIcon(getNotificationIcon()) // required
                    .setContentText(description)  // required
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setLargeIcon(BitmapFactory.decodeResource
                            (getResources(), R.mipmap.logo))
                    .setBadgeIconType(R.mipmap.logo)
                    .setContentIntent(pendingIntent)
                    .setSound(RingtoneManager.getDefaultUri
                            (RingtoneManager.TYPE_NOTIFICATION));
            Notification notification = builder.build();
            notifManager.notify(0, notification);
        } else {

            Intent intent = new Intent(this, Dashboard.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = null;

            pendingIntent = PendingIntent.getActivity(this, 1251, intent, PendingIntent.FLAG_ONE_SHOT);

            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setContentTitle(title)
                    .setContentText(description)
                    .setAutoCancel(true)
                    .setColor(ContextCompat.getColor(getBaseContext(), R.color.colorPrimary))
                    .setSound(defaultSoundUri)
                    .setSmallIcon(getNotificationIcon())
                    .setContentIntent(pendingIntent)
                    .setStyle(new NotificationCompat.BigTextStyle().setBigContentTitle(title).bigText(description));

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(1251, notificationBuilder.build());
        }
    }

    private int getNotificationIcon() {
        boolean useWhiteIcon = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
        return useWhiteIcon ? R.mipmap.logo : R.mipmap.logo;
    }
}
7
ответ дан Mohsinali 15 August 2018 в 17:47
поделиться
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "CHANNEL_ID")
            ........

    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = "Hello";// The user-visible name of the channel.
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
        mNotificationManager.createNotificationChannel(mChannel);
    }
    mNotificationManager.notify(notificationId, notificationBuilder.build());
-2
ответ дан Vasily Kabunov 15 August 2018 в 17:47
поделиться
0
ответ дан Attaullah 5 September 2018 в 16:52
поделиться
0
ответ дан Micklo_Nerd 5 September 2018 в 16:52
поделиться
Другие вопросы по тегам:

Похожие вопросы: