2016-08-14 85 views
2

正如标题所示,我希望使用FCM发送有效内容并加载位图以在通知大图中使用它。我试过这种方法(代码如下)来获取图像,但它没有奏效。任何帮助深表感谢使用FCM加载通知大图片

谢谢

String imageUrl; 

/** 
* Called when message is received. 
* 
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging. 
*/ 
// [START receive_message] 
@Override 
public void onMessageReceived(RemoteMessage remoteMessage) { 
    // TODO(developer): 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. See sendNotification method below. 

    Intent intent = new Intent(this, MainActivity.class); 
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, 
      PendingIntent.FLAG_ONE_SHOT); 

    if (remoteMessage.getData().size() > 0) { 
     imageUrl = remoteMessage.getData().toString(); 
    } 

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
    Notification.Builder notificationBuilder = new Notification.Builder(this) 
      .setSmallIcon(R.drawable.ic_launcher) 
      .setContentTitle("Glaze") 
      .setContentText(remoteMessage.getNotification().getBody()) 
      .setAutoCancel(true) 
      .setSound(defaultSoundUri) 
      .setLargeIcon(getBitmap(imageUrl)) 
      .setStyle(new Notification.BigPictureStyle().bigPicture(getBitmap(imageUrl))) 
      .setContentIntent(pendingIntent); 

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

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

    Log.d(TAG, "From: " + remoteMessage.getFrom()); 
    Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody()); 
} 
// [END receive_message] 

public static Bitmap getBitmap(String src) { 
    try { 
     URL url = new URL(src); 
     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; 
    } 
} 
+0

如果要在通知中显示图像,则必须使用RemoteViews。 – shivamDev

+0

远程视图?如果可能,你可以进一步解释它吗 –

+0

通过这个链接:https://developer.android.com/reference/android/widget/RemoteViews.html你也可以搜索例子。 – shivamDev

回答

0

您需要使用NotificationCompat.BigPictureStyle一个大画面的布局。另外,您必须在从网址加载位图后发布通知。

+0

我正在使用此Notification.BigPictureStyle()而不是Notification Compat。我正在获取该样式,但图像未加载。我应该如何加载它之前,任何代码示例? –

+1

您可以使用AsyncTask从'doInBackground()'中的url下载图像,并从'onPostExecute()'发布通知。 [类似问题](https://stackoverflow.com/questions/24840282/load-image-from-url-in-notification-android) – Bhav