【问题标题】:Firebase massagingFirebase 消息传递
【发布时间】:2021-01-28 07:22:53
【问题描述】:

我正在尝试在 andorid 中处理来自 FCM(Firebase Cloud Messaging) 的消息;

这是我的代码

 FirebaseMessaging.getInstance().getToken()
                .addOnCompleteListener(new OnCompleteListener<String>() {
                    @Override
                    public void onComplete(@NonNull Task<String> task) {
                        if (!task.isSuccessful()) {
                            Log.w("TAG", "Fetching FCM registration token failed", task.getException());
                            return;
                        }

                        // Get new FCM registration token
                        String token = task.getResult();

                        // Log and toast
                        Log.d("TAG", token);
                        Toast.makeText(StartActivity.this, token, Toast.LENGTH_SHORT).show();
                    }
                });
        FirebaseMessaging.getInstance().setAutoInitEnabled(true);

我已经从 firebase 控制台发送了消息。

但我想处理这些消息。 所以我做了这个文档说https://firebase.google.com/docs/cloud-messaging/android/receive

这是 manifest.xml

  <service
            android:name="com.google.firebase.messaging.FirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
            
            <meta-data
                android:name="com.google.firebase.messaging.default_notification_icon"
                android:resource="@android:drawable/ic_notification_overlay" />
        
            <meta-data
                android:name="com.google.firebase.messaging.default_notification_color"
                android:resource="@color/white" />

            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>

        </service>

这是我的 FirebaseMessagingService 扩展类

public class MessageService extends FirebaseMessagingService {

    private static final String TAG = "MessageService";


    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Toast.makeText(this, "Got it", Toast.LENGTH_SHORT).show();
    }
}

但我不知道如何将此 FirebaseMessagingService 类重新注册到 Firebase 消息传递

【问题讨论】:

    标签: java android firebase firebase-cloud-messaging


    【解决方案1】:

    您不需要注册消息服务的类,您需要注册应用程序本身。它应该是项目中的 google-services.json 配置文件,其中包含有关 firebase 控制台中项目的所有必要信息。它将在您的应用和在 Firebase 控制台中创建的项目之间建立某种联系。

    获取这个配置文件有几种方式:

    1. 通过 Firebase 控制台生成 google-services.json https://firebase.google.com/docs/cloud-messaging/android/client#register_your_app_with_firebase
    2. 通过 Android Studio 生成它。工具 -> Firebase -> 云消息传递 -> 完成向导“设置 Firebase 云消息传递”

    【讨论】:

    • 好的,谢谢,但我确实在 Manifest.xml 文件中犯了一个错误。
    【解决方案2】:

    你在 manifest.xml 文件中做错了。

    你必须替换它

    <service
                android:name="com.google.firebase.messaging.FirebaseMessagingService"
                android:exported="false">
                <intent-filter>
                    <action android:name="com.google.firebase.MESSAGING_EVENT" />
                </intent-filter>
                
                <meta-data
                    android:name="com.google.firebase.messaging.default_notification_icon"
                    android:resource="@android:drawable/ic_notification_overlay" />
            
                <meta-data
                    android:name="com.google.firebase.messaging.default_notification_color"
                    android:resource="@color/white" />
    
                <intent-filter>
                    <action android:name="com.google.firebase.MESSAGING_EVENT" />
                </intent-filter>
    
            </service>
    

    有了这个

    <service android:name=".helpers.MyFirebaseInstanceIDService">
                <intent-filter>
                    <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
                </intent-filter>
            </service>
            <service android:name=".helpers.MyFirebaseMessagingService">
                <intent-filter>
                    <action android:name="com.google.firebase.MESSAGING_EVENT" />
                </intent-filter>
            </service>
    

    并创建这些类

    MyFirebaseInstanceIDService

    public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
        public void onTokenRefresh() {
            // Get updated InstanceID token.
            String refreshedToken = FirebaseInstanceId.getInstance().getToken();
            Log.d("TAG", "Refreshed token: " + refreshedToken);
    
            // If you want to send messages to this application instance or
            // manage this apps subscriptions on the server side, send the
            // Instance ID token to your app server.
        }
    }
    

    和 MyFirebaseMessagingService

    public class MyFirebaseMessagingService extends FirebaseMessagingService {
        private static final String TAG = "DEEDDEED";
    
        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
    
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                public void run() {
                    Toast.makeText(MyFirebaseMessagingService.this,"Hello",Toast.LENGTH_SHORT).show();
                }
            });
            // ...
    
            // TODO(developer): Handle FCM messages here.
            
            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.
        }
    
        @Override
        public void onNewToken(@NonNull String s) {
            super.onNewToken(s);
    
            HashMap<String,String> map = new HashMap<>();
            Database database = new Database(getApplicationContext());
            map.put("user",database.getPhone());
            map.put("token",s);
            Call<Void> call = new Server().getRetrofitInterface().executeUpdatePTK(map);
            call.enqueue(new Callback<Void>() {
                @Override
                public void onResponse(Call<Void> call, Response<Void> response) {
    
                }
    
                @Override
                public void onFailure(Call<Void> call, Throwable t) {
    
                }
            });
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      相关资源
      最近更新 更多