Xamarin.Forms의 Android 장치에 알림을 보내도록 FCM에 앱을 설정했지만 알림 만 수신되지만 시스템 트레이에 이미지가 표시되지 않습니다.
이것은 내 AndroidManifest.xml입니다.
<application android:label="DMSMobileApp.Android">
<receiver
android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver"
android:exported="false" />
<receiver
android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="${applicationId}" />
</intent-filter>
</receiver>
</application>
FirebaseMessagingService.cs를 만들어 로컬 알림을 받고 변환했습니다.
[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
const string TAG = "MyFirebaseMsgService";
public override void OnMessageReceived(RemoteMessage message)
{
var body = message.GetNotification().Body;
Log.Debug(TAG, "Notification Message Body: " + body);
SendNotification(body, message.Data);
//new NotificationHelper().CreateNotification(message.GetNotification().Title, message.GetNotification().Body);
}
void SendNotification(string messageBody, IDictionary<string, string> data)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
foreach (var key in data.Keys)
{
intent.PutExtra(key, data[key]);
}
var pendingIntent = PendingIntent.GetActivity(this,
MainActivity.NOTIFICATION_ID,
intent,
PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
.SetSmallIcon(Resource.Drawable.notification_template_icon_bg)
.SetContentTitle("FCM Message")
.SetContentText(messageBody)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(MainActivity.NOTIFICATION_ID, notificationBuilder.Build());
}
}
그리고 REST API로 알림을 보냅니다.
var data = new
{
to = "/topics/ALL", // Recipient device token
notification = new {
title = "Test",
body = "Message",
image = "https://cdn.pixabay.com/photo/2015/05/15/14/38/computer-768608_960_720.jpg"
},
image = "https://cdn.pixabay.com/photo/2015/05/15/14/38/computer-768608_960_720.jpg"
};
var jsonBody = JsonConvert.SerializeObject(data);
bool fcmState;
using (var httpRequest = new HttpRequestMessage(HttpMethod.Post, "https://fcm.googleapis.com/fcm/send"))
{
httpRequest.Headers.TryAddWithoutValidation("Authorization", serverKey);
httpRequest.Headers.TryAddWithoutValidation("Sender", senderId);
httpRequest.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
var result = await httpClient.SendAsync(httpRequest);
if (result.IsSuccessStatusCode)
{
fcmState = true;
}
else
{
// Use result.StatusCode to handle failure
// Your custom error handler here
//_logger.LogError($"Error sending notification. Status Code: {result.StatusCode}");
}
}
}
FCM에서 이미지 데이터를받는 동안 이미지를 다운로드하여 문제를 해결했습니다. 여기 내 코드가 있습니다.
void SendNotification(string messageBody, IDictionary<string, string> data, RemoteMessage message)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
foreach (var key in data.Keys)
{
intent.PutExtra(key, data[key]);
}
var pendingIntent = PendingIntent.GetActivity(this,
MainActivity.NOTIFICATION_ID,
intent,
PendingIntentFlags.OneShot);
//var test = message.GetNotification().Body;
string title = data["title"];
string body = data["body"];
string imageReceived = data["image"]; //It contains image URL.
GetImageBitmapFromUrl(imageReceived); // This method will download image from URL.
var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
.SetSmallIcon(Resource.Drawable.logo)
.SetContentTitle(title)
.SetContentText(body)
.SetStyle(new NotificationCompat.BigPictureStyle().BigPicture(imageBitmap)) //// This will show the image in system tray.
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(MainActivity.NOTIFICATION_ID, notificationBuilder.Build());
}
데이터 IDictionary의 '이미지'키에 링크가있는 경우 이미지를 다운로드하는 코드입니다.
Bitmap imageBitmap = null;
Bitmap roundedImage = null;
public Bitmap GetImageBitmapFromUrl(string url)
{
using (var webClient = new System.Net.WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
roundedImage = Bitmap.CreateScaledBitmap(imageBitmap, 300, 300, false);
//roundedImage = getRoundedShape(resizedImage);
}
webClient.Dispose();
}
return roundedImage;
}
REST API를 통해 FCM으로 보내는 데이터입니다. @Harikrishnan 덕분에 처음에는 nofitication 개체를 사용했지만 작동했지만 이미지 데이터가 없었습니다.
var data = new
{
to = "/topics/ALL", // Recipient device token
data = new {
title = "Test",
body = "Message",
image = "https://cdn.pixabay.com/photo/2015/05/15/14/38/computer-768608_960_720.jpg"
},
};
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다