gpt4 book ai didi

android - FirebaseMessagingService - 如何从后台更新数据库或 SharedPreferences?

转载 作者:搜寻专家 更新时间:2023-10-30 22:34:18 25 4
gpt4 key购买 nike

我正在尝试在收到来自 Firebase 控制台的推送通知后更新应用程序数据库。它在应用程序运行时有效,但是当应用程序在后台或进程被终止时,我无法更改 SharedPreferences 中的数据。

但是使用 NotificationManager 发送通知是有效的。从 Firebase 检索推送通知时,有什么方法可以更新数据库吗?

 private void sendNotification(String messageBody) {
Intent intent = new Intent(this, EventListActivityDrawerNewMenu.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_launcher)
.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());
}

private void saveDataToPreferences(String data) {
Context context = this;
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(UpdateDataService.MY_PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(UpdateDataService.MY_PREFS_NAME, data);
editor.commit();
}

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
android.os.Debug.waitForDebugger();

Log.d(TAG, "From: " + remoteMessage.getFrom());

if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}

if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}

saveDataToPreferences(remoteMessage.getNotification().getBody());

}

最佳答案

好的,我已经解决了这个问题。 Firebase 有两种类型的推送通知:显示消息和数据消息。并且只有数据消息才能唤醒您的服务以更新数据库。您不能从 firebase 控制台创建数据消息,您只能通过 url 上的 post 请求发送它:

https://fcm.googleapis.com/fcm/send

正文:

{
"data": {
"data" : "some message",
"other_key" : true
},
"registration_ids": ["here your user token", "another user token"]}

标题:

  • 键:内容类型,值:application/json

  • 键:授权,值:key=your-server-key

关于android - FirebaseMessagingService - 如何从后台更新数据库或 SharedPreferences?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39390031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com