Уведомление Firebase не появляется на устройстве - PullRequest
0 голосов
/ 24 апреля 2018

Я приостанавливаю свое приложение в OnTokenRefresh(), копирую токен, помещаю приложение в фоновый режим, а затем отправляю сообщение с помощью консоли Firebase, в котором говорится, что токен не зарегистрирован.

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

Почему это происходит?

1 Ответ

0 голосов
/ 24 апреля 2018

Да, в старом Firebase Cloud Messaging это было так, но вы можете получать данные из firebase и генерировать уведомления с помощью бодрствующего широковещательного приемника

public class FirebaseDataReceiver extends WakefulBroadcastReceiver {
    private Utils utils = new Utils();

    @Override
    public void onReceive(Context context, Intent intent) {
        String mediaType = intent.getExtras().getString("mediaType");
//        Log.e("BroadcastReceiver::", "BroadcastReceiver");
        if (mediaType != null) {
            String message = intent.getExtras().getString("message");
            String imageUri = intent.getExtras().getString("image");
            String newsId = intent.getExtras().getString("newsId");
            Intent floating = new Intent(context, ChatHeadService.class);
            floating.putExtra("imageUri", imageUri);
            floating.putExtra("newsId", newsId);
            floating.putExtra("message", message);
            floating.putExtra("mediaType", mediaType);
            Bitmap bitmap = getBitmapfromUrl(imageUri, context);
            sendNotification(context, message, bitmap, imageUri, newsId, mediaType, null);
            if (Build.VERSION.SDK_INT >= 23) {
                if (!Settings.canDrawOverlays(context)) {
                    utils.cToast("Please enable Overlay permission for My News", context);
                    Intent settingIntent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                            Uri.parse("package:" + context.getPackageName()));
                    settingIntent.addFlags(FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(settingIntent);
                } else if (utils.getPrefernces(context, "dnd") == null)
                    context.startService(floating);
                else if (utils.getPrefernces(context, "dnd").equalsIgnoreCase("true"))
                    context.startService(floating);
            } else if (utils.getPrefernces(context, "dnd") == null)
                context.startService(floating);
            else if (utils.getPrefernces(context, "dnd").equalsIgnoreCase("true"))
                context.startService(floating);
        }
    }

    public void sendNotification(Context context, String messageBody, Bitmap image, String imageUri, String newsId, String mediaType, String TrueOrFalse) {
        Intent intent = null;

        switch (mediaType) {

            case "print":

                intent = new Intent(context, FullPrintMedia.class);
//                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra("nid", newsId);
                intent.putExtra("mediaType", mediaType);
                break;

            case "electronic":

                intent = new Intent(context, FullElectronicMedia.class);
//                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra("nid", newsId);
                intent.putExtra("mediaType", mediaType);
                break;

            case "live":

                intent = new Intent(context, Live.class);
//                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                break;

            case "update":

                //Open the app page in Google Play store:
                intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=live.mynews.app"));
                intent.addFlags(FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                break;

            case "add_friend":

                intent = new Intent(context, Collapsinglayout.class);
                intent.putExtra("userId", newsId);
                intent.putExtra("userName", messageBody.substring(0, messageBody.indexOf(' ')));
                intent.putExtra("userImage", imageUri);
                intent.putExtra("isFriend", 3);
                break;

            case "accept_friend":

                intent = new Intent(context, Collapsinglayout.class);
                intent.putExtra("userId", newsId);
                intent.putExtra("userName", messageBody.substring(0, messageBody.indexOf(' ')));
                intent.putExtra("userImage", imageUri);
                intent.putExtra("isFriend", 0);
                break;

            default:

                intent = new Intent(context, FullPrintMedia.class);
//                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra("nid", newsId);
                intent.putExtra("mediaType", mediaType);
                break;
        }

//        intent.putExtra("AnotherActivity", TrueOrFalse);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 /* Request code */, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
                .setLargeIcon(image)/*Notification icon image*/
                .setSmallIcon(new MyUtils().getNotificationIcon())
                .setContentTitle(messageBody)
                .setColor(ContextCompat.getColor(context, R.color.orange))
                .setStyle(new NotificationCompat.BigPictureStyle()
                        .bigPicture(image))/*Notification with Image*/
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setPriority(Notification.PRIORITY_MAX)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }

    public Bitmap getBitmapfromUrl(String imageUrl, Context context) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            return BitmapFactory.decodeStream(input);
//            return bitmap;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.noimageavailable);
            e.printStackTrace();
            return icon;
        }
    }
}

У меня была та же проблема и я написал эту логику, которая помогла мне решить эту проблему.

Но если вы обновите SDK, он получит уведомления как в фоновом, так и на переднем плане

...