Уведомления Android не отображаются на kitkat - PullRequest
0 голосов
/ 07 июня 2018

Я пытаюсь показать уведомления от Firebase Messaging, он работает на oreo и выше, но воспроизводит звук только на устройствах kitkat (у меня нет других устройств или эмуляторов для тестирования), и я получаю некоторые странные журналы ошибок, такие как

Could not find class 'android.app.Notification$Action$Builder', referenced 
from method android.support.v4.app.NotificationCompatBuilder.addAction

Я действительно изо всех сил пытаюсь определить это, поэтому вот основная часть кода

private void sendNotification(Map<String, String> data) {

    String author = data.get("USER_NAME");
    String title = data.get("TITLE");
    String body = data.get("BODY");
    String id = data.get("USER_NUMBER");
    String message = data.get("MESSAGE");
    String type = data.get("TYPE");
    String image = data.get("IMAGE");
    String profileImage = data.get("USER_IMAGE");
    String shortMessage = "";
    Intent intent;
    Bitmap bitmap;
    Bitmap bitmap2;

    intent = new Intent(this, MessageListActivity.class);
    if (MessageListActivity.isAppRunning)
        intent = new Intent(this, MainActivity.class);

    intent.putExtra(Constants.USER_NAME, author);
    intent.putExtra(Constants.USER_NUMBER, id);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    /*
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(intent);
    */
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);
    /*
    String replyLabel = getString(R.string.notif_action_reply);
    RemoteInput remoteInput = new RemoteInput.Builder(KEY_REPLY)
            .setLabel(replyLabel)
            .build();
    */
    // If the message is longer than the max number of characters we want in our
    // notification, truncate it and add the unicode character for ellipsis
    if (message.length() > NOTIFICATION_MAX_CHARACTERS) {
        shortMessage = message.substring(0, NOTIFICATION_MAX_CHARACTERS) + "\u2026";
    }
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    if (type.equals("IMAGE")) {
        bitmap = getBitmapfromUrl(image);
        bitmap2 = getBitmapfromUrl(profileImage);
        notificationBuilder
                .setLargeIcon(bitmap2)
                .setSmallIcon(R.drawable.message_me)
                .setContentTitle(String.format(getString(R.string.notification_message), author))
                .setStyle(new NotificationCompat.BigPictureStyle()
                        .setSummaryText(shortMessage)
                        .bigPicture(bitmap))
                .setContentText(message)
                .setColor(getResources().getColor(R.color.colorPrimary))
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);
    } else if (type.equals("TEXT")) {
        bitmap2 = getBitmapfromUrl(profileImage);
        notificationBuilder
                .setSmallIcon(R.drawable.message_me)
                .setLargeIcon(bitmap2)
                .setContentTitle(String.format(getString(R.string.notification_message), author))
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText(message))
                .setContentText(shortMessage)
                .setColor(getResources().getColor(R.color.colorPrimary))
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
            && Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
        notificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
        getManager().notify(0 /* ID of notification */, notificationBuilder.build());
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        notificationBuilder = getChannelNotification(title, body, shortMessage, SINGLE_CHANNEL_ID, pendingIntent, type, image, profileImage);
        getManager().notify(0, notificationBuilder.build());
    }
}



private NotificationManager getManager() {
    if (mManager == null) {
        mManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    }
    return mManager;
}

все данные присутствуют и исправьте первую ошибку, которую я получаю, это

 Could not find class 'android.app.NotificationChannel', referenced from 
 method com.sealstudios.aimessage.MyFirebaseMessagingService.createChannels

, и мой метод createChannels это

@RequiresApi(api = Build.VERSION_CODES.O)
public void createChannels() {
    // create single channel
    NotificationChannel singleChannel = new NotificationChannel(SINGLE_CHANNEL_ID,
            SINGLE_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
    singleChannel.enableLights(true);
    singleChannel.enableVibration(true);
    singleChannel.setLightColor(R.color.colorPrimary);
    singleChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
    getManager().createNotificationChannel(singleChannel);

    // create group channel
    NotificationChannel groupChannel = new NotificationChannel(GROUP_CHANNEL_ID,
            GROUP_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
    groupChannel.enableLights(true);
    groupChannel.enableVibration(true);
    groupChannel.setLightColor(R.color.colorPrimary);
    groupChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
    getManager().createNotificationChannel(groupChannel);
}

, но он вызывается только из onMessageReceived в скобке if, как это

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // Check if message contains a data payload.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        createChannels();
    }
    if (remoteMessage.getData().size() > 0) {
        Map<String, String> data = remoteMessage.getData();
        if (data.size() > 0) {
            if (!(chatActive && remoteMessage.getData().get("USER_NAME").equals(senderID))) {
                //TODO add a mute notifications
                sendNotification(data);
            }
        }
    }
    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {

    }
}

, как уже упоминалось, я получаю полное уведомлениебез каких-либо забот на Android Oreo из-за отдельного метода, который это

@RequiresApi(api = Build.VERSION_CODES.O)
public NotificationCompat.Builder getChannelNotification(String title, 
String body, String smallMessage, String channelId,
                                                         PendingIntent pendingIntent, String type, String largeImage,
                                                         String smallImage) {


    if (type.equals("TEXT")) {
        Bitmap smallBitmap = getBitmapfromUrl(smallImage);
        return new NotificationCompat.Builder(getApplicationContext())
                .setChannelId(channelId)
                .setContentTitle(title)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(body))
                .setContentText(body)
                .setColor(getResources().getColor(R.color.colorPrimary))
                .setSmallIcon(R.drawable.message_me)
                .setLargeIcon(smallBitmap)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);
    } else if (type.equals("IMAGE")) {
        Bitmap smallBitmap = getBitmapfromUrl(smallImage);
        Bitmap largeBitmap = getBitmapfromUrl(largeImage);
        return new NotificationCompat.Builder(getApplicationContext())
                .setChannelId(channelId)
                .setContentTitle(title)
                .setStyle(new NotificationCompat.BigPictureStyle().setSummaryText(smallMessage).bigPicture(largeBitmap))
                .setContentText(body)
                .setColor(getResources().getColor(R.color.colorPrimary))
                .setSmallIcon(R.drawable.message_me)
                .setLargeIcon(smallBitmap)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);
    }
    return new NotificationCompat.Builder(getApplicationContext())
            .setChannelId(channelId)
            .setContentTitle(title)
            .setContentText(body)
            .setColor(getResources().getColor(R.color.colorPrimary))
            .setSmallIcon(R.drawable.message_me)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);
}

, но в противном случае я просто получаю звук уведомления, я уверен, что он работал до того, как я поднял целевой SDK до 27, но любая помощьбыл бы признателен

1 Ответ

0 голосов
/ 07 июня 2018

похоже, что это было исправлено обновлением подключаемых модулей

...