如何使用 Json 文件初始化 RemoteMessage 对象?
Posted
技术标签:
【中文标题】如何使用 Json 文件初始化 RemoteMessage 对象?【英文标题】:How to initialize a RemoteMessage object with a Json file? 【发布时间】:2017-11-03 19:19:34 【问题描述】:我正在处理 FCM 消息,我有以下功能:
public void onMessageReceived(final RemoteMessage remoteMessage)
final Map<String, String> data = remoteMessage.getData();
//...
出于测试目的,我有一个包含数据的 Json 文件,我想将该 Json 文件从我的测试方法发送到 onMessagereceived()
。因此,我需要使用 Json 文件初始化 RemoteMessage
对象,并将此 RemoteMessage 对象传递给函数。如何初始化它?
我的 JSON 文件:
"data":
"id" : "4422",
"type" : "1",
"imageUrl" : "https://image.freepik.com/free-vector/android-boot-logo_634639.jpg",
"smallTitle" : "DoJMA v2",
"smallSubTitle" : "Update now from Google Play Store",
"ticker" : "New update for DoJMA",
"contentInfo" : "",
"link" : "https://photo2.tinhte.vn/data/avatars/l/1885/1885712.jpg?1402763583",
"className" : "HomeActivity",
"page" : "2",
"bigTitle" : "DoJMA Android app version 2 released!",
"bigSubTitle" : "Hi folks! New DoJMA update is here! Major redesigning and improvements! This app was made by the Mobile App Club.They work really hard man...and get good products",
"bigSummaryText" : "Update now"
,
"registration_ids": ["dQYmpLUACXQ:APA91bGl-NoIMJ2_DcctF5-OA8ghyWuyrMfsz3uhlj1BySl6axkAsmv5y_7YGfpQQJ2E0lP_fTcxphpZdkJzY1tbcWA36e78ooxC_b0a1PAank9gFIAUHVZkHKmZT70MPZosCgvRlVfq","dfLXnRI36qY:APA91bFyjLblijVIjGLCGWVeB1B0z5j_3TYqRytJ-8hvuUESpDlX59gWF3hU-I-kA4VrRCPpEVFWl18ZarnPjqxxtZgFkVxoLr77HRex27VN7Mh3xupWykmKq_nnVIlVzrODKwKI7ktM"]
【问题讨论】:
在 JSONObject 中传递你的数据 json = new JSONObject("Your json String"); onMessageReceived 方法内部。 @Janak 但如何将其转换为 remoteMessage 对象? 你想要这个 Json 在你的响应中? @Janak 我想将此 Json 传递给onMessageReceived()
,因此我必须将其转换为 RemoteMessage
对象。我的问题是如何做到这一点。
【参考方案1】:
您可以使用 Postman For Single User 进行测试。
使用 JSON 负载发送通知
网址:https://fcm.googleapis.com/fcm/send
标题:
Authorization: key=<your-api-key>
Content-Type: application/json
正文(点击“原始”标签):
"to": "dQYmpLUACXQ:APA91bGl-NoIMJ2_DcctF5-OA8ghyWuyrMfsz3uhlj1BySl6axkAsmv5y_7YGfpQQJ2E0lP_fTcxpHpZdkJzY1tbcWA36e78ooxC_b0a1PAank9gFIAUHVZkHKmZT70MPZosCgvRlVfq",
"data":
"id": "4422",
"type": "1",
"imageUrl": "https://image.freepik.com/free-vector/android-boot-logo_634639.jpg",
"smallTitle": "DoJMA v2",
"smallSubTitle": "Update now from Google Play Store",
"ticker": "New update for DoJMA",
"contentInfo": "",
"link": "https://photo2.tinhte.vn/data/avatars/l/1885/1885712.jpg?1402763583",
"className": "HomeActivity",
"page": "2",
"bigTitle": "DoJMA Android app version 2 released!",
"bigSubTitle": "Hi folks! New DoJMA update is here! Major redesigning and improvements! This app was made by the Mobile App Club.They work really hard man...and get good products",
"bigSummaryText": "Update now"
来源:https://firebase.google.com/docs/cloud-messaging/concept-options
【讨论】:
【参考方案2】:TL;DR:初始化RemoteMessage
对象不可能。
尝试从您自己的类中访问初始化 RemoteMessage 将返回错误:
“RemoteMessage(android.os.Bundle)”在“com.google.firebase.messaging.RemoteMessage”中不公开。无法从外部包访问。
我想您是出于测试目的而尝试这样做(存根?)。一般来说(不会说最佳实践,因为我不完全确定这是最佳实践),建议有一个接受特定的单独方法您需要的价值。参考official example (onMessageReceived
)(删除了一些东西):
@Override
public void onMessageReceived(RemoteMessage remoteMessage)
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0)
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
if (/* Check if data needs to be processed by long running job */ true)
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
scheduleJob();
else
// Handle message within 10 seconds
handleNow();
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null)
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
// 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.
/**
* Schedule a job using FirebaseJobDispatcher.
*/
private void scheduleJob()
// [START dispatch_job]
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("my-job-tag")
.build();
dispatcher.schedule(myJob);
// [END dispatch_job]
/**
* Handle time allotted to BroadcastReceivers.
*/
private void handleNow()
Log.d(TAG, "Short lived task is done.");
/**
* Create and show a simple notification containing the received FCM message.
*
* @param messageBody FCM message body received.
*/
private void sendNotification(String messageBody)
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);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
关注提到的评论:
此外,如果您打算根据收到的 FCM 消息生成自己的通知,则应在此处启动。请参阅下面的 sendNotification 方法。
这指出了接受字符串参数的sendNotification()
方法。根据您的情况,您可以简单地传递您的方法需要的对象,而不是尝试传递初始化的RemoteMessage
(遗憾的是这是不可能的,或者至少是不可取的) .
这样,您几乎测试了处理消息的方法,而不依赖于不是您最初创建的类的对象。
PS:我的一些解释可能会令人困惑,但我希望这是有道理的。
【讨论】:
以上是关于如何使用 Json 文件初始化 RemoteMessage 对象?的主要内容,如果未能解决你的问题,请参考以下文章
如何给现有工程初始化一个react-native环境的package.json