图片未显示在推送通知中

时间:2019-08-30 11:26:35

标签: android firebase firebase-cloud-messaging

我正在使用下面的通知有效负载,并使用Postman将推送通知发送到Android设备:

{
    "to" : "/topics/xxxx" ,
    "data" : {
        "url" : "https://res.cloudinary.com/demo/image/upload/w_200/lady.jpg",
        "dl" : ""
    },
    "notification" : {
        "title" : "This is a sample notification from general2",
        "body" : "Rich notification testing (body)",
        "image": "https://res.cloudinary.com/demo/image/upload/w_200/lady.jpg"
    }

}

我使用了image键值对在推送通知中包含图片。我的预期输出是:

enter image description here

但这是电话中显示的内容:

enter image description here

如您所见,图像没有出现。可能是什么问题?

6 个答案:

答案 0 :(得分:2)

我发现问题出在电池节电器上。例如,小米和三星(尤其是Android 11)手机会限制FCM进行后台联网(获取图像),因此会丢失图像。这只会在手机处于深度睡眠状态时发生。如果不是(并且您的应用程序已关闭或在后台),则会显示图像。如果应用在前台,onMessageReceived() 将被调用,您无论如何都需要手动获取图像,并且不会受到电话限制。

遗憾的是,我没有找到任何解决方法,除了用户手动为您的应用禁用电池节省功能:/

enter image description here

答案 1 :(得分:1)

简而言之 将图像上传到流行的图像托管网站并将该链接用于通知图像 url 对我有用。还要检查我使用的图像大小(1000 × 500 像素)

展开 我也面临同样的问题,但创建 MyFirebaseMessagingService 没有帮助。 我试图从自己的主机加载图像(https://www.example.com/image/img.png)。 虽然它是 https 并且 firebase 控制台显示图像,但在实际设备上它没有显示。

对我来说,将图片上传到 imggur.com 或将其放入 firbase 存储并使用该链接进行通知,无需任何额外的消息服务代码。

答案 2 :(得分:0)

此代码可能会帮助

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMessagingServ";

    Target target = new Target() {
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            sendNotification(bitmap);
        }

        @Override
        public void onBitmapFailed(Exception e, Drawable errorDrawable) {

        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {

        }
    };

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        if(remoteMessage.getData()!=null)
            getImage(remoteMessage);
    }

    private void sendNotification(Bitmap bitmap){


        NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
        style.bigPicture(bitmap);

        Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent,0);

        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        String NOTIFICATION_CHANNEL_ID = "101";

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification", NotificationManager.IMPORTANCE_MAX);

            //Configure Notification Channel
            notificationChannel.setDescription("Game Notifications");
            notificationChannel.enableLights(true);
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            notificationChannel.enableVibration(true);

            notificationManager.createNotificationChannel(notificationChannel);
        }

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setContentTitle(Config.title)
                .setAutoCancel(true)
                .setSound(defaultSound)
                .setContentText(Config.content)
                .setContentIntent(pendingIntent)
                .setStyle(style)
                .setLargeIcon(bitmap)
                .setWhen(System.currentTimeMillis())
                .setPriority(Notification.PRIORITY_MAX);


        notificationManager.notify(1, notificationBuilder.build());


    }

    private void getImage(final RemoteMessage remoteMessage) {

        Map<String, String> data = remoteMessage.getData();
        Config.title = data.get("title");
        Config.content = data.get("content");
        Config.imageUrl = data.get("imageUrl");
        Config.gameUrl = data.get("gameUrl");
        //Create thread to fetch image from notification
        if(remoteMessage.getData()!=null){

            Handler uiHandler = new Handler(Looper.getMainLooper());
            uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    // Get image from data Notification
                    Picasso.get()
                            .load(Config.imageUrl)
                            .into(target);
                }
            }) ;
        }
    }
}

答案 3 :(得分:0)

您必须自己处理图像的接收,如官方文档最后一行所述: 如图所示设置通知,此发送请求使接收客户端能够处理有效负载中传递的图像。 Firesebase official documentation

答案 4 :(得分:0)

2021 年工作解决方案:

else setText("");

答案 5 :(得分:-1)

首先像这样创建类

package com.lokal.aja.Config;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.lokal.aja.Activity.MainActivity;
import com.lokal.aja.R;

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        Log.d("msg", "onMessageReceived: " + remoteMessage.getData().get("message"));

        //on notification is clicked
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        String channelId = "Default";
        NotificationCompat.Builder builder = new  NotificationCompat.Builder(this, channelId)
                .setSmallIcon(R.drawable.ic_main_logo)
                .setContentTitle(remoteMessage.getNotification().getTitle())
                .setContentText(remoteMessage.getNotification().getBody()).setAutoCancel(true).setContentIntent(pendingIntent);;
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
            manager.createNotificationChannel(channel);
        }
        manager.notify(0, builder.build());
    }
}

然后你应该把这个类添加到 AndroidManifest

<service android:name=".MyFirebaseMessagingService">
      <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
</service>