我正在制作一个 VoIP 应用程序。如何确保来电通知,即使应用程序处于后台?谷歌 FCM 仅在应用程序处于前台时工作(可能是由于 android 电池优化)。 Whatsapp 和 Telegram 做了什么来确保近 100% 的来电通知?
onMessageReceived
应用程序在后台时不会调用方法。
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getData().toString());
}
}
附言 通过Telegram's codebase我发现他们总是在前台运行他们的应用程序
<service android:name=".BringAppForegroundService" android:enabled="true"/>
他们是这样解决通知问题的,还是比表面上看到的更多?
最佳答案
去找你的后端开发人员,告诉他不要在 firebase 通知中使用通知对象。仅发送带有 to 参数的 data 对象。
不要从服务器发送 Notification 对象。因为如果您在 json
中使用 notification
对象,当您的应用处于后台时,您的应用将不会显示推送通知。
例如
{
"to": "e1w6hEbZn-8:APA91bEUIb2JewYCIiApsMu5JfI5Ak...",
"notification": {
"body": "Cool offers. Get them before expiring!",
"title": "Flat 80% discount",
"icon": "appicon"
}
}
您的后端开发人员必须像这样发送 json:
{
"data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}
如果您使用仅数据消息
,在这两种情况下都会调用onMessageReceived() 方法,即使您的应用程序处于前台
或背景
。然后只需使用 键值
即可获得响应。
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
...
Map<String, String> data = remoteMessage.getData();
//you can get your text message here.
String text= data.get("text");
...
}
关于android - whatsapp/telegram 如何确保来电通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49706194/