获取Android中用于FCM的消息令牌的正确方式是什么?

huangapple go评论94阅读模式
英文:

What is the correct way to get the messaging token for FCM in Android?

问题

以下是翻译好的内容:

UPDATE

在与Doug的对话中,我解决了我的问题。首先,我专注于这个类中的onNewToken()方法,并在构造函数中删除了我的getToken()请求。

public class PushNotificationManager extends FirebaseMessagingService {

    public String MT;

    public PushNotificationManager() {

    }

    @Override
    public void onNewToken(String token) {
        super.onNewToken(token);
        MT =  token;
        System.out.println("Refreshed token: " + token);
    }
}

这个与清单文件的更新相结合,会在应用启动后完全重新安装后记录消息令牌。现在,要将令牌存储在Firebase RTB中,我需要在初始化数据库之后访问它。所以我在我的数据库类中添加了一个方法,在数据库初始化之后调用该方法。它看起来像这样:

private void setMT()
{
    FirebaseInstanceId.getInstance().getInstanceId()
            .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                @Override
                public void onComplete(@NonNull Task<InstanceIdResult> task) {
                    if (!task.isSuccessful()) {
                        //Log.w(TAG, "getInstanceId failed", task.getException());
                        return;
                    }

                    // 获取新的实例ID令牌
                    String MT = (String) task.getResult().getToken();
                    System.out.println("Messaging token: " + MT);
                    // 现在我可以将其保存到RTB中
                }
            });
}

现在它正常工作了!感谢Doug的帮助!

英文:

Good evening!

I am looking to add Firebase cloud messaging to my project (Android, Java). I have followed the documentation
https://firebase.google.com/docs/cloud-messaging/android/client#retrieve-the-current-registration-token
to a tee, but am still having issues retrieving the messaging token. Android studio claims Cannot resolve method 'getToken' in 'FirebaseMessaging' and will not compile. I assume I need to write a method getToken(), but can not find any documentation on what that method should do.

Here is my class, which extends FirebaseMessagingService as the documentation describes.

public class PushNotificationManager extends FirebaseMessagingService {

    public String MT;

    public PushNotificationManager() {
        FirebaseMessaging.getInstance().getToken()
                .addOnCompleteListener(new OnCompleteListener&lt;String&gt;() {
            @Override
            public void onComplete(@NonNull Task&lt;String&gt; task) {
                if (!task.isSuccessful()) {
                    System.out.println(&quot;Failed to get token&quot;);
                    return;
                }
                MT = task.getResult();

            }
        });
    }

    @Override
    public void onNewToken(String token) {
        super.onNewToken(token);
        MT =  token;
        System.out.println(&quot;Refreshed token: &quot; + token);
    }
}

I also override onNewToken(), per the docs, but I never get a print to the logs.

Here is the service I added to the manifest:

        &lt;service android:name=&quot;.PushNotificationManager&quot;&gt;
            &lt;intent-filter&gt;
                &lt;action android:name=&quot;com.google.firebase.MESSAGING_EVENT&quot; /&gt;
            &lt;/intent-filter&gt;
        &lt;/service&gt;

There are a number of old stack overflow articles about this subject, but none have worked, most are older than a year, and use InstanceID() which is now depreciated.

Any suggestions? Thank you for your time!

UPDATE

Thanks to my conversation below with Doug, I have solved my issue. Firstly, I focused on onNewToken() in this class, and deleted my getToken() request in the constructor.

public class PushNotificationManager extends FirebaseMessagingService {

    public String MT;

    public PushNotificationManager() {

    }

    @Override
    public void onNewToken(String token) {
        super.onNewToken(token);
        MT =  token;
        System.out.println(&quot;Refreshed token: &quot; + token);
    }
}

This, in combination with the updates to the manifest file, logs the messaging token on app start up After a complete reinstall. Now, to store the token in Firebase RTB, I need to access this after I initialize the database. So I added a method in my database class, which is called after the database is initialized. It looks like this:

    private void setMT()
    {
        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnCompleteListener(new OnCompleteListener&lt;InstanceIdResult&gt;() {
                    @Override
                    public void onComplete(@NonNull Task&lt;InstanceIdResult&gt; task) {
                        if (!task.isSuccessful()) {
                            //Log.w(TAG, &quot;getInstanceId failed&quot;, task.getException());
                            return;
                        }

                        // Get new Instance ID token
                        String MT = (String) task.getResult().getToken();
                        System.out.println(&quot;Messaging token: &quot;+MT);
//Now I can save it to the RTB
                    }
                });
    }

And now its working! Thanks for the help, Doug!

答案1

得分: 0

如果您在已注册的FirebaseMessagingService子类中覆盖了onNewToken方法,那么您就不需要其他任何内容来获取令牌。您可以使用getToken按需获取令牌,或者通过onNewToken回调接收它。除非您确切知道需要这样做(尤其是在同一个类中),否则没有太多理由同时执行这两种操作。

如果您没有收到关于onNewToken的回调,那么您可能没有完全遵循说明,将FirebaseMessagingService子类添加为Android服务到您的清单中。

英文:

If you are overriding onNewToken in a registered subclass of FirebaseMessagingService, then you don't need anything else to get a token. You either fetch it on demand with getToken, or you receive it via callback with onNewToken. There is little reason to do both (especially in the same class), unless you absolutely know you need to.

If you don't get a callback to onNewToken, then you probably didn't fully follow the instructions and add your subclass of FirebaseMessagingService as an Android service in your manifest.

huangapple
  • 本文由 发表于 2020年10月28日 08:23:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/64564761.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定