本文介绍了Firebase (FCM) 如何获取令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次使用 FCM.

我从

代码:

RegistrationIntentService.java

public class RegistrationIntentService extends IntentService {private static final String TAG =RegIntentService";公共注册意图服务(){超级(标记);}@覆盖受保护的无效 onHandleIntent(意图意图){String token = FirebaseInstanceId.getInstance().getToken();Log.i(TAG,FCM注册令牌:"+令牌);}}

MyFirebaseInstanceIDService.java

public class MyFirebaseInstanceIDService 扩展 FirebaseInstanceIdService {private static final String TAG =MyFirebaseIIDService";/*** 在 InstanceID 令牌更新时调用.如果安全性可能会发生这种情况* 之前的令牌已被泄露.请注意,当 InstanceID 令牌* 最初生成,因此您可以在此处检索令牌.*///[开始刷新令牌]@覆盖公共无效 onTokenRefresh() {//获取更新的 InstanceID 令牌.//String refreshedToken = FirebaseInstanceId.getInstance().getToken();//Log.d(TAG, "Refreshed token: " + refreshedToken);//////TODO:实现此方法以将任何注册发送到您的应用程序的服务器.//sendRegistrationToServer(refreshedToken);//Intent intent = new Intent(this, RegistrationIntentService.class);开始服务(意图);}//[END refresh_token]/*** 将令牌持久化到第三方服务器.* <p>* 修改此方法,将用户的 FCM InstanceID 令牌与任何服务器端帐户相关联* 由您的应用程序维护.** @param token 新的令牌.*/私人无效sendRegistrationToServer(字符串令牌){//根据需要添加自定义实现.}}

在 MainActivity.java 中添加这个.

 Intent intent = new Intent(this, RegistrationIntentService.class);开始服务(意图);

完成上述操作后,您将获得Logcat中的Token.但最后,我找到了一种方便的方式来获取它.只需使用调试模式安装示例应用,您就可以在第一次安装时获取令牌.

但是不知道为什么我安装的时候不能打印日志.可能跟手机系统有关.

然后为什么我无法收到通知.FirebaseMessagingService.onMessageReceived 没有调用 sendNotification

解决方案

最快最好的原型

快速解决方案是将其存储在 sharedPrefs 中,并将此逻辑添加到 MainActivity 或扩展应用程序的类中的 onCreate 方法.

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(this, instanceIdResult -> {String newToken = instanceIdResult.getToken();Log.e(newToken", newToken);getActivity().getPreferences(Context.MODE_PRIVATE).edit().putString("fb", newToken).apply();});Log.d("newToken", getActivity().getPreferences(Context.MODE_PRIVATE).getString("fb", "empty :("));

更清洁的方式

更好的选择是创建一个服务并保持在类似的逻辑中.首先新建一个Service

public class MyFirebaseMessagingService 扩展 FirebaseMessagingService {@覆盖公共无效onNewToken(字符串s){super.onNewToken(s);Log.e(newToken", s);getSharedPreferences("_", MODE_PRIVATE).edit().putString("fb", s).apply();}@覆盖public void onMessageReceived(RemoteMessage remoteMessage) {super.onMessageReceived(remoteMessage);}公共静态字符串 getToken(上下文上下文){返回 context.getSharedPreferences("_", MODE_PRIVATE).getString("fb", "empty");}}

然后将其添加到AndroidManifest文件中

<意图过滤器><action android:name="com.google.firebase.MESSAGING_EVENT"/></意图过滤器></服务>

最后,您可以使用服务中的静态方法 MyFirebaseMessagingService.getToken(Context);

最快但已弃用

Log.d(Firebase", token"+ FirebaseInstanceId.getInstance().getToken());

当您使用比 17.x.x 版本更旧的 firebase 库时,它仍然有效

It's my first time using FCM.

I download a sample from firebase/quickstart-android and I install the FCM Quickstart. But I can't get any token from the log even hit the LOG TOKEN button in the app.

Then I try to send a message with Firebase console and set to target my app package name. I got incoming messages.

I want to know can FCM be used?GCM everything is ok.

Solution:

Because I am not an Android developer, just a backend developer. So it takes me some time to solve it. In my opinion, there`re some bugs in the sample app.

Code:

RegistrationIntentService.java

public class RegistrationIntentService extends IntentService {

    private static final String TAG = "RegIntentService";


    public RegistrationIntentService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String token = FirebaseInstanceId.getInstance().getToken();
        Log.i(TAG, "FCM Registration Token: " + token);
    }
}

MyFirebaseInstanceIDService.java

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. Note that this is called when the InstanceID token
     * is initially generated so this is where you would retrieve the token.
     */
    // [START refresh_token]
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
//        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//        Log.d(TAG, "Refreshed token: " + refreshedToken);
//
//        // TODO: Implement this method to send any registration to your app's servers.
//        sendRegistrationToServer(refreshedToken);
//
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }
    // [END refresh_token]

    /**
     * Persist token to third-party servers.
     * <p>
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
        // Add custom implementation, as needed.
    }
}

Add this in the MainActivity.java.

 Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);

After do above,you get the Token in Logcat. But finally, I find a convenient way to get it.Just use debug mode to install the sample app and you can get the token when you first time to install it.

But I don't know why it can't print the log when I install it. Maybe be related to the mobile system.

And then why I can't get the Notification. FirebaseMessagingService.onMessageReceived did not call sendNotification

解决方案

FASTEST AND GOOD FOR PROTOTYPE

The quick solution is to store it in sharedPrefs and add this logic to onCreate method in your MainActivity or class which is extending Application.

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(this, instanceIdResult -> {
    String newToken = instanceIdResult.getToken();
    Log.e("newToken", newToken);
    getActivity().getPreferences(Context.MODE_PRIVATE).edit().putString("fb", newToken).apply();
});

Log.d("newToken", getActivity().getPreferences(Context.MODE_PRIVATE).getString("fb", "empty :("));

CLEANER WAY

A better option is to create a service and keep inside a similar logic. Firstly create new Service

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.e("newToken", s);
        getSharedPreferences("_", MODE_PRIVATE).edit().putString("fb", s).apply();
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
    }

    public static String getToken(Context context) {
        return context.getSharedPreferences("_", MODE_PRIVATE).getString("fb", "empty");
    }
}

And then add it to AndroidManifest file

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

Finally, you are able to use a static method from your Service MyFirebaseMessagingService.getToken(Context);

THE FASTEST BUT DEPRECATED

Log.d("Firebase", "token "+ FirebaseInstanceId.getInstance().getToken());

It's still working when you are using older firebase library than version 17.x.x

这篇关于Firebase (FCM) 如何获取令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 05:13