gpt4 book ai didi

java - FCM 数据消息无法正常工作

转载 作者:行者123 更新时间:2023-11-29 23:45:42 25 4
gpt4 key购买 nike

我正在使用数据消息,即使应用程序被终止、在后台或在前台,我们也可以发送消息。我正在使用 FCM。但就我而言,有时我的应用程序没有收到这些消息。我正在从应用程序向应用程序发送消息。有时应用程序即使在被杀死或从后台删除时也会收到消息,但有时它不会。当我打开应用程序时,突然出现消息。当收到特定消息时,我正在打开 Activity 。我知道即使应用程序被终止或在后台或在前台,数据消息也用于发送消息,但我遇到了这样的问题。请帮忙 !..我希望它是绝对的。我只希望我的应用程序始终连接到 FirebaseMessagingServices,即使它已被杀死。我不知道服务,有人说我需要创建一个前台服务。如何创建它并实现到 FirebaseMessagingServices 。?

MYFirebaseMessaging.java

package com.example.praful.ubercoustomer.Service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

import com.example.praful.ubercoustomer.AcceptedWindow;
import com.example.praful.ubercoustomer.Common.Common;
import com.example.praful.ubercoustomer.CompanycancelledtheBooking;
import com.example.praful.ubercoustomer.DeclinedWindow;
import com.example.praful.ubercoustomer.Helper.NotificationHelper;
import com.example.praful.ubercoustomer.Onthewayandimreached;
import com.example.praful.ubercoustomer.R;
import com.example.praful.ubercoustomer.RateActivity;
import com.example.praful.ubercoustomer.VerifyingCompletedBooking;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import java.util.Map;

public class MyFirebaseMessaging extends FirebaseMessagingService {
@Override
public void onMessageReceived(final RemoteMessage remoteMessage) {


if (remoteMessage.getData() != null) {
Map<String, String> data = remoteMessage.getData();
String title = data.get("title");
final String companyName = data.get("CompanyName");
final String BookingIdC = data.get("BookingIdC");
final String BookingIdT = data.get("BookingIdT");
final String companyPhone = data.get("CompanyPhone");
final String companyRates = data.get("CompanyRates");
final String companyId = data.get("CompanyId");
final String Date = data.get("Date");
final String companyIdC = data.get("companyIdC");
final String Time = data.get("Time");
final String Id = data.get("Id");
final String Address = data.get("Address");
final String Bookingid = data.get("Bookingid");
final String TimeCB = data.get("TimeCB");
final String DateCB = data.get("DateCB");
final String EventType = data.get("EventType");
final String messageCB = data.get("messageCB");
final String AddressCB = data.get("AddressCB");
final String companythatcancelledthebooking = data.get("CompanyNamethatcancelledthebooking");

final String message = data.get("message");
// remoteMessage.getNotification().getTitle() = title and remoteMessage.getNotification().getBody() = message
if (title != null && title.equals("Cancel")) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(MyFirebaseMessaging.this, DeclinedWindow.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(intent);

Common.isCompanyFound = false;
Common.companyId = "";
Toast.makeText(MyFirebaseMessaging.this, "" + message, Toast.LENGTH_SHORT).show();
}
});
} else if (title != null && title.equals("cancelAdvanceBooking")) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(getBaseContext(), CompanycancelledtheBooking.class);
intent.putExtra("DateCB", DateCB);
intent.putExtra("TimeCB", TimeCB);
intent.putExtra("messageCB", messageCB);
intent.putExtra("AddressCB", AddressCB);
intent.putExtra("EventType", EventType);
intent.putExtra("Id", Id);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(intent);

Common.isCompanyFound = false;
Common.companyId = "";
Toast.makeText(MyFirebaseMessaging.this, "" + messageCB, Toast.LENGTH_SHORT).show();
}
});

} else if (title != null && title.equals("Accept")) {


Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(MyFirebaseMessaging.this, AcceptedWindow.class);
intent.putExtra("Date", Date);
intent.putExtra("Time", Time);
intent.putExtra("Address", Address);
intent.putExtra("companyName", companyName);
intent.putExtra("companyPhone", companyPhone);
intent.putExtra("companyRates", companyRates);
intent.putExtra("companyId", companyId);
intent.putExtra("Bookingid", Bookingid);
intent.putExtra("EventType", EventType);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(intent);
Common.isCompanyFound = false;
Common.companyId = "";


Toast.makeText(MyFirebaseMessaging.this, "" + message, Toast.LENGTH_SHORT).show();
}
});

} else if (title != null && title.equals("Arrived")) {
Handler handler = new Handler(Looper.getMainLooper());

handler.post(new Runnable() {
@Override
public void run() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
showArrivedNotifAPI26(message);
else
showArrivedNotif(message);

}
});
} else if (title != null && title.equals("Completed")) {

openRateactivity(message);
} else if (title != null && title.equals("completedAdvancebooking")) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(MyFirebaseMessaging.this, VerifyingCompletedBooking.class);
intent.putExtra("BookingIdC", BookingIdC);
intent.putExtra("message", message);
intent.putExtra("companyid", companyIdC);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(intent);

}
});
} else if (title != null && title.equals("Ontheway")) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(MyFirebaseMessaging.this, Onthewayandimreached.class);
intent.putExtra("message", message);
intent.putExtra("BookingIdT", BookingIdT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(intent);

}
});
} else if (title != null && title.equals("Reached")) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(MyFirebaseMessaging.this, Onthewayandimreached.class);
intent.putExtra("message", message);
intent.putExtra("BookingIdT", BookingIdT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(intent);

}
});
}

}
}

@RequiresApi(api = Build.VERSION_CODES.O)
private void showArrivedNotifAPI26(String body) {
PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(), 0,
new Intent(), PendingIntent.FLAG_ONE_SHOT);

Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationHelper notificationHelper = new NotificationHelper(getBaseContext());
Notification.Builder builder = notificationHelper.getUberNotification("Arrived", body, contentIntent, defaultSound);
notificationHelper.getManager().notify(1, builder.build());

}

private void openRateactivity(String body) {

Intent intent = new Intent(this, RateActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}

private void showArrivedNotif(String body) {
PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(), 0,
new Intent(), PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext());
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
.setWhen(System.currentTimeMillis()).
setSmallIcon(R.drawable.ic_menu_camera)
.setContentTitle("Arrived")
.setContentText(body)
.setContentIntent(contentIntent);

NotificationManager manager = (NotificationManager) getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1, builder.build());
}

}

MyFirebaseIdService

package com.example.praful.ubercoustomer.Service;

import com.example.praful.ubercoustomer.Common.Common;
import com.example.praful.ubercoustomer.Model.Token;
import com.example.praful.ubercoustomer.Common.Common;
import com.example.praful.ubercoustomer.Model.Token;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

public class MyFirebaseIdService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
super.onTokenRefresh();

String refreshedToken = FirebaseInstanceId.getInstance().getToken();
updateTokenToServer(refreshedToken);

}

private void updateTokenToServer(String refreshedToken) {

FirebaseDatabase db =FirebaseDatabase.getInstance();
DatabaseReference tokens = db.getReference(Common.token_table);

Token token = new Token(refreshedToken);
if(FirebaseAuth.getInstance().getCurrentUser() != null)
tokens.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(token);

}
}

最佳答案

  • 首先检查此远程消息包含负载,负载可能因任何原因损坏。

    public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "REMOTE_MSG";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
    if (remoteMessage == null)
    return;

    // check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
    Log.e(TAG, "Notification body: " + remoteMessage.getNotification().getBody());
    createNotification(remoteMessage.getNotification());
    }

    // check if message contains a data payload
    if (remoteMessage.getData().size() > 0) {
    Log.d(TAG, "From: " + remoteMessage.getFrom());
    Log.d(TAG, "Message data payload: " + remoteMessage.getData());
    }
    }
  • 不要忘记在您的数据库上更新您的 FCM 设备 token 。

    public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {
    private static final String TAG = "FCM_ID";

    @Override
    public void onTokenRefresh() {
    // get hold of the registration token
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    // lg the token
    Log.d(TAG, "Refreshed token: " + refreshedToken);
    sendRegistrationToServer(refreshedToken);
    }
    private void sendRegistrationToServer(String token) {
    // implement this method if you want to store the token on your server
    }
    }

更新 1

  • 如前所述Firebase repo issue预计该问题与设备有关,请尝试其他设备方面。

更新 2 引自 firebase repo贡献者 kroikie

FCM does not process messages if an app is "killed" or force stopped. When a user kills an app it is an indication that the user does not want the app running so that app should not run till the user explicitly starts it again.

Note that swiping an app from recents list should NOT "kill" or force stop it. If messages are not being received after swiping from recents list then please identify these devices and we will work with the manufactures to correct this behaviour.

Only being able to handle messages when the app is in the foreground or background is working as intended.

更新 3

  • 尝试在这个问题上提到的技巧。

    1. 在 Manifest.xml 中插入此行

      <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
      <uses-permission android:name="android.permission.WAKE_LOCK" />
    2. 这是因为 DOZE 模式和电池优化,您只需关闭所有应用程序或特定应用程序的电池优化。转到设置>>应用>>选择您的应用>>电池>>电池优化> 选择您的应用>> 选择不优化。问题解决了。

    3. 现在(对于 APP IS CLOSED 的情况)我将通知文本写入文件并在 extras == null 和 notificationText.txt 存在时读取此文本...这是愚蠢的解决方案,但它有效。当应用程序以其他方式关闭时,我如何捕获这些额外内容。

更新 4

Users can manually configure the whitelist in Settings > Battery > Battery Optimization. Alternatively, the system provides ways for apps to ask users to whitelist them.

An app can fire the ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS intent to take the user directly to the Battery Optimization, where they can add the app. An app holding the REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission can trigger a system dialog to let the user add the app to the whitelist directly, without going to settings. The app fires a ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS Intent to trigger the dialog. The user can manually remove apps from the whitelist as needed.

  • 以编程方式打开电池优化,检查此 answer .

注意这个

Before asking the user to add your app to the whitelist, make sure the app matches the acceptable use cases for whitelisting.

Note: Google Play policies prohibit apps from requesting direct exemption from Power Management features in Android 6.0+ (Doze and App Standby) unless the core function of the app is adversely affected.

更新 5

  • 检查 PowerManager.isIgnoringBatteryOptimizations()来自这个answer .

  • 当禁用电池优化时,考虑先检查它是否已经禁用然后不需要显示对话框,否则你可以显示对话框。

     /**
    * return false if in settings "Not optimized" and true if "Optimizing battery use"
    */
    private boolean checkBatteryOptimized() {
    final PowerManager pwrm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    try {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    return !pwrm.isIgnoringBatteryOptimizations(getBaseContext().getPackageName());
    }
    }catch (Exception ignored){}
    return false;
    }

    private void startBatteryOptimizeDialog(){
    try {
    Intent intent = new Intent(android.provider.Settings.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
    intent.setData(Uri.parse("package:PUT_YOUR_PACKAGE_NAME_HERE"));
    startActivity(intent);

    } catch (ActivityNotFoundException e) {
    e.printStackTrace();
    }
    }

关于java - FCM 数据消息无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51460652/

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