Android 在Firebase通知内传递图像时出错

Android 在Firebase通知内传递图像时出错,android,image,firebase,android-bitmap,firebase-notifications,Android,Image,Firebase,Android Bitmap,Firebase Notifications,我试图在FireBase通知中传递图像,但它向我显示了解析json对象的错误 bellow是显示错误的日志cat 这是从服务器发送数据的json {"to":"dJ4ege8LbI8:APA91bGqGQyIEBn2TsSnb7yZjv-2RjRCK8L1mqzxDnP0_lJBDvAPu7QzF7SVmb_gBmpo2n7w97B9mPjHpDOdDaPb-CDhngKZMOO4Xc79lrhTImsuVicf2mZOquVkhHq1JBR-KAcLf-9F","notification":{

我试图在FireBase通知中传递图像,但它向我显示了解析json对象的错误 bellow是显示错误的日志cat

这是从服务器发送数据的json

{"to":"dJ4ege8LbI8:APA91bGqGQyIEBn2TsSnb7yZjv-2RjRCK8L1mqzxDnP0_lJBDvAPu7QzF7SVmb_gBmpo2n7w97B9mPjHpDOdDaPb-CDhngKZMOO4Xc79lrhTImsuVicf2mZOquVkhHq1JBR-KAcLf-9F","notification":{"body":"gdshgh","title":"jkhds","icon":"myicon","sound":"mysound","click_action":"OPEN_ACTIVITY"},"data":{"image":"http://www.propertynewsindia.in/wp-content/uploads/2013/11/Buy-A-New-Home.jpg"}}
这是一个有效的json输出 请帮忙,先谢谢你

MyFirebaseMessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
NotificationUtils notificationUtils;
String imageUrl;

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // TODO: Handle FCM messages here.
    // If the application is in the foreground handle both data and notification messages here.
    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated.
    Log.e(TAG, "From: " + remoteMessage.getFrom());

    if (remoteMessage == null)
        return;

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
        handleNotification(remoteMessage.getNotification().getBody());
    }

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

        try {
            JSONObject json = new JSONObject(remoteMessage.getData().toString());
            handleDataMessage(json);
        }catch (JSONException je){
            Log.e(TAG,"JSONException: "+je.getMessage());
        }
        catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
        NotificationCompat.Builder builder = new  NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("test")
                .setContentText(remoteMessage.getData().get("message"));
        NotificationManager manager = (NotificationManager)     getSystemService(NOTIFICATION_SERVICE);
        manager.notify(0, builder.build());
}
private void handleNotification(String message) {
    if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
        // app is in foreground, broadcast the push message
        Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
        pushNotification.putExtra("message", message);
        LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

        // play notification sound
        notificationUtils = new NotificationUtils(getApplicationContext());
        notificationUtils.playNotificationSound();
        notificationUtils.getBitmapFromURL(imageUrl);
    }else{
        // If the app is in background, firebase itself handles the notification
    }
}

private void handleDataMessage(JSONObject json) {
    Log.e(TAG, "push json: " + json.toString());

    try {
        JSONObject data = json.getJSONObject("data");

        String title = data.getString("title");
        String message = data.getString("message");
        boolean isBackground = data.getBoolean("is_background");
        String imageUrl = data.getString("image");
        String timestamp = data.getString("timestamp");
        JSONObject payload = data.getJSONObject("payload");

        Log.e(TAG, "title: " + title);
        Log.e(TAG, "message: " + message);
        Log.e(TAG, "isBackground: " + isBackground);
        Log.e(TAG, "payload: " + payload.toString());
        Log.e(TAG, "imageUrl: " + imageUrl);
        Log.e(TAG, "timestamp: " + timestamp);


        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the` push message
            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound
            notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
        } else {
            // app is in background, show the notification in notification tray
            Intent resultIntent = new Intent(getApplicationContext(), Home.class);
            resultIntent.putExtra("message", message);

            // check for image attachment
            if (TextUtils.isEmpty(imageUrl)) {
                showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
            } else {
                // image is present, show notification with image
                showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Json Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}

/**
 * Showing notification with text only
 */
private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
}

/**
 * Showing notification with text and image
 */
private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
}
}

通知

public class NotificationUtils {
private static String TAG = NotificationUtils.class.getSimpleName();

private Context mContext;

public NotificationUtils(Context mContext) {
    this.mContext = mContext;
}

public void showNotificationMessage(String title, String message, String timeStamp, Intent intent) {
    showNotificationMessage(title, message, timeStamp, intent, null);
}

public void showNotificationMessage(final String title, final String message, final String timeStamp, Intent intent, String imageUrl) {
    // Check for empty push message
    if (TextUtils.isEmpty(message))
        return;


    // notification icon
    final int icon = R.mipmap.ic_launcher;

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    final PendingIntent resultPendingIntent =
            PendingIntent.getActivity(
                    mContext,
                    0,
                    intent,
                    PendingIntent.FLAG_CANCEL_CURRENT
            );

    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            mContext);

    final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
            + "://" + mContext.getPackageName() + "/raw/notification");

    if (!TextUtils.isEmpty(imageUrl)) {

        if (imageUrl != null && imageUrl.length() > 4 && Patterns.WEB_URL.matcher(imageUrl).matches()) {

            Bitmap bitmap = getBitmapFromURL(imageUrl);

            if (bitmap != null) {
                showBigNotification(bitmap, mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
            } else {
                showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
            }
        }
    } else {
        showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
        playNotificationSound();
    }
}


private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

    inboxStyle.addLine(message);

    Notification notification;
    notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentIntent(resultPendingIntent)
            .setSound(alarmSound)
            .setStyle(inboxStyle)
            .setWhen(getTimeMilliSec(timeStamp))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
            .setContentText(message)
            .build();

    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(Config.NOTIFICATION_ID, notification);
}

private void showBigNotification(Bitmap bitmap, NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {
    NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
    bigPictureStyle.setBigContentTitle(title);
    bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
    bigPictureStyle.bigPicture(bitmap);
    Notification notification;
    notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentIntent(resultPendingIntent)
            .setSound(alarmSound)
            .setStyle(bigPictureStyle)
            .setWhen(getTimeMilliSec(timeStamp))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
            .setContentText(message)
            .build();

    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(Config.NOTIFICATION_ID_BIG_IMAGE, notification);
}

/**
 * Downloading push notification image before displaying it in
 * the notification tray
 */
public Bitmap getBitmapFromURL(String strURL) {
    try {
        Log.i("URL-IMAGE",strURL);
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

// Playing notification sound
public void playNotificationSound() {
    try {
        Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                + "://" + mContext.getPackageName() + "/raw/notification");
        Ringtone r = RingtoneManager.getRingtone(mContext, alarmSound);
        r.play();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * Method checks if the app is in background or not
 */
public static boolean isAppIsInBackground(Context context) {
    boolean isInBackground = true;
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                        isInBackground = false;
                    }
                }
            }
        }
    } else {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        if (componentInfo.getPackageName().equals(context.getPackageName())) {
            isInBackground = false;
        }
    }

    return isInBackground;
}

// Clears notification tray messages
public static void clearNotifications(Context context) {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancelAll();
}

public static long getTimeMilliSec(String timeStamp) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        Date date = format.parse(timeStamp);
        return date.getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return 0;
}
公共类通知utils{
私有静态字符串标记=NotificationUtils.class.getSimpleName();
私有上下文;
公共通知UTILS(上下文mContext){
this.mContext=mContext;
}
public void showNotificationMessage(字符串标题、字符串消息、字符串时间戳、意图){
showNotificationMessage(标题、消息、时间戳、意图、空);
}
public void showNotificationMessage(最终字符串标题、最终字符串消息、最终字符串时间戳、意图、字符串图像URL){
//检查空推送消息
if(TextUtils.isEmpty(message))
返回;
//通知图标
最终int图标=R.mipmap.ic_启动器;
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP | intent.FLAG_ACTIVITY_SINGLE_TOP);
最终挂起内容结果挂起内容=
pendingent.getActivity(
McContext,
0,
意图
PendingEvent.FLAG_取消_当前
);
最终NotificationCompat.Builder mBuilder=新NotificationCompat.Builder(
mContext);
最终Uri alarmSound=Uri.parse(ContentResolver.SCHEME\u ANDROID\u资源
+“:/”+mContext.getPackageName()+“/raw/notification”);
如果(!TextUtils.isEmpty(imageUrl)){
if(imageUrl!=null&&imageUrl.length()>4&&Patterns.WEB\u URL.matcher(imageUrl.matches()){
位图位图=getBitmapFromURL(imageUrl);
if(位图!=null){
showBigNotification(位图、mBuilder、图标、标题、消息、时间戳、结果结束内容、alarmSound);
}否则{
showSmallNotification(mBuilder、图标、标题、消息、时间戳、ResultPendingContent、alarmSound);
}
}
}否则{
showSmallNotification(mBuilder、图标、标题、消息、时间戳、ResultPendingContent、alarmSound);
播放通知声音();
}
}
私有void showSmallNotification(NotificationCompat.Builder mBuilder、int图标、字符串标题、字符串消息、字符串时间戳、PendingEvent ResultPendingEvent、Uri alarmSound){
NotificationCompat.InboxStyle InboxStyle=新NotificationCompat.InboxStyle();
inboxStyle.addLine(消息);
通知;
通知=mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(真)
.setContentTitle(标题)
.setContentIntent(结果结束内容)
.setSound(警报声)
.setStyle(收件箱样式)
.setWhen(GetTimeMillissec(时间戳))
.setSmallIcon(R.mipmap.ic_启动器)
.setLargeIcon(位图工厂.decodeResource(mContext.getResources(),图标))
.setContentText(消息)
.build();
NotificationManager NotificationManager=(NotificationManager)mContext.getSystemService(Context.NOTIFICATION\u服务);
notificationManager.notify(Config.NOTIFICATION\u ID,NOTIFICATION);
}
私有void showBigNotification(位图位图、NotificationCompat.Builder mBuilder、int图标、字符串标题、字符串消息、字符串时间戳、PendingEvent ResultPendingEvent、Uri alarmSound){
NotificationCompat.BigPictureStyle BigPictureStyle=新NotificationCompat.BigPictureStyle();
bigPictureStyle.setBigContentTitle(标题);
bigPictureStyle.setSummaryText(Html.fromHtml(message.toString());
bigPictureStyle.bigPicture(位图);
通知;
通知=mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(真)
.setContentTitle(标题)
.setContentIntent(结果结束内容)
.setSound(警报声)
.setStyle(大图片样式)
.setWhen(GetTimeMillissec(时间戳))
.setSmallIcon(R.mipmap.ic_启动器)
.setLargeIcon(位图工厂.decodeResource(mContext.getResources(),图标))
.setContentText(消息)
.build();
NotificationManager NotificationManager=(NotificationManager)mContext.getSystemService(Context.NOTIFICATION\u服务);
notificationManager.notify(Config.NOTIFICATION\u ID\u BIG\u IMAGE,NOTIFICATION);
}
/**
*在中显示推送通知图像之前下载该图像
*通知盘
*/
公共位图getBitmapFromURL(字符串strURL){
试一试{
Log.i(“URL-IMAGE”,strURL);
URL=新URL(strURL);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream输入=连接。getInputStream();
位图myBitmap=BitmapFactory.decodeStream(输入);
返回我的位图;
}捕获(IOE异常){
e、 printStackTrace();
返回null;
}
}
//播放通知音
公共无效播放通知声音(){
试一试{
Uri alarmSound=Uri.parse(ContentResolver.SCHEME\u ANDROID\u资源
+“:/”+mContext.getPackageName()+“/raw/notification”);
Ringtone r=RingtoneManager.getRingtone(mContext,alarmSound);
r、 play();
}捕获(例外e){
e、 printStackTrace();
}
}
/**
*方法检查应用程序是否在后台
*/
公共静态布尔值isAppIsInBackground(上下文){
布尔值isInBackground=true;
ActivityManager am=(ActivityManager)context.getSystemService(context.ACTIVITY_服务);
if(Build.VERSION.SDK\u INT>Build.VERSION\u code.KITKAT\u WATCH){

列表

当前,在通知数据中仅发送1个值“图像”,但读取其他值
{
   {
   "to":"dJ4ege8LbI8:APA91bGqGQyIEBn2TsSnb7yZjv-2RjRCK8L1mqzxDnP0_lJBDvAPu7QzF7SVmb_gBmpo2n7w97B9mPjHpDOdDaPb-CDhngKZMOO4Xc79lrhTImsuVicf2mZOquVkhHq1JBR-KAcLf-9F",
   "notification":{  
      "body":"gdshgh",
      "title":"jkhds",
      "icon":"myicon",
      "sound":"mysound",
      "click_action":"OPEN_ACTIVITY"
   },
   "data":{  
      "data":{  
         "image":"http://www.propertynewsindia.in/wp-content/uploads/2013/11/Buy-A-New-Home.jpg"
      },
      "title":"My title",
      "message":"My message",
      "is_background":true,
      "timestamp:"2017-07-31 05:42:12",
      "payload":{  
         "name":"Test"
      }
   }
}
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
NotificationUtils notificationUtils;
String imageUrl;

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // TODO: Handle FCM messages here.
    // If the application is in the foreground handle both data and notification messages here.
    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated.
    Log.e(TAG, "From: " + remoteMessage.getFrom());

    if (remoteMessage == null)
        return;

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null && remoteMessage.getData().size()==0) {
        Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
        handleNotification(remoteMessage.getNotification().getBody());
    }

    // Check if message contains a data payload.
    else if (remoteMessage.getData().size() > 0) {
        Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

        try {
            JSONObject json = new JSONObject(remoteMessage.getData().getString("data"));
            handleDataMessage(json);
        }catch (JSONException je){
            Log.e(TAG,"JSONException: "+je.getMessage());
        }
        catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
        NotificationCompat.Builder builder = new  NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("test")
                .setContentText(remoteMessage.getData().get("message"));
        NotificationManager manager = (NotificationManager)     getSystemService(NOTIFICATION_SERVICE);
        manager.notify(0, builder.build());
}
private void handleNotification(String message) {
    if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
        // app is in foreground, broadcast the push message
        Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
        pushNotification.putExtra("message", message);
        LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

        // play notification sound
        notificationUtils = new NotificationUtils(getApplicationContext());
        notificationUtils.playNotificationSound();
    }else{
        // If the app is in background, firebase itself handles the notification
    }
}

private void handleDataMessage(JSONObject json) {
    Log.e(TAG, "push json: " + json.toString());

    try {

        String title = json.getString("title");
        String message = json.getString("message");
        boolean isBackground = json.getBoolean("is_background");
        String imageUrl = json.getString("image");
        String timestamp = json.getString("timestamp");
        JSONObject payload = json.getJSONObject("payload");

        Log.e(TAG, "title: " + title);
        Log.e(TAG, "message: " + message);
        Log.e(TAG, "isBackground: " + isBackground);
        Log.e(TAG, "payload: " + payload.toString());
        Log.e(TAG, "imageUrl: " + imageUrl);
        Log.e(TAG, "timestamp: " + timestamp);


        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the` push message
            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound
            notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
        } else {
            // app is in background, show the notification in notification tray
            Intent resultIntent = new Intent(getApplicationContext(), Home.class);
            resultIntent.putExtra("message", message);

            // check for image attachment
            if (TextUtils.isEmpty(imageUrl)) {
                showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
            } else {
                // image is present, show notification with image
                showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Json Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}

/**
 * Showing notification with text only
 */
private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
}

/**
 * Showing notification with text and image
 */
private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
}