希望你们所有人都知道这个类,用来获取通知令牌,每当firebase通知令牌被刷新时,我们从这个类获得刷新令牌,从下面的方法。

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);
}

使用这个,因为我想实现FCM,我扩展MyClass从FirebaseInstanceIdService

但是,显示FirebaseInstanceIdService已弃用

有人知道吗?, 我应该使用什么方法或类,而不是这个来获得刷新令牌,因为这是不赞成的。

我正在使用:实现'com.google.firebase:firebase-messaging:17.1.0'

我检查了文件,没有提到这一点。: FCM设置文件


更新

此问题已修复。

由于谷歌已弃用FirebaseInstanceService,

我问了这个问题来找到方法,我知道我们可以从FirebaseMessagingService获得令牌,

像以前一样,当我问问题时,文档没有更新,但现在谷歌文档更新了,因此要了解更多信息,请参考谷歌文档:FirebaseMessagingService

From: FirebaseInstanceService(已弃用)

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);
}

NEW From: FirebaseMessagingService

@Override
public void onNewToken(String s) {
    super.onNewToken(s);
    Log.d("NEW_TOKEN",s);
}

当前回答

对于kotlin,我使用以下方法

val fcmtoken = FirebaseMessaging.getInstance().token.await()

对于扩展函数

public suspend fun <T> Task<T>.await(): T {
    // fast path
    if (isComplete) {
        val e = exception
        return if (e == null) {
            if (isCanceled) {
                throw CancellationException("Task $this was cancelled normally.")
            } else {
                @Suppress("UNCHECKED_CAST")
                result as T
            }
        } else {
            throw e
        }
    }

    return suspendCancellableCoroutine { cont ->
        addOnCompleteListener {
            val e = exception
            if (e == null) {
                @Suppress("UNCHECKED_CAST")
                if (isCanceled) cont.cancel() else cont.resume(result as T)
            } else {
                cont.resumeWithException(e)
            }
        }
    }
}

其他回答

在build.gradle上添加这个。 实现“com.google.firebase: firebase-messaging: 20.2.3”

下面是c# /Xamarin的解决方案。Android:

var token = await FirebaseInstallations.Instance.GetToken(forceRefresh: false).AsAsync<InstallationTokenResult>();

更新11-12-2020

现在FirebaseInstanceId也被弃用了

现在我们需要使用FirebaseMessaging.getInstance().token

示例代码

        FirebaseMessaging.getInstance().token.addOnCompleteListener {
            if(it.isComplete){
                firebaseToken = it.result.toString()
                Util.printLog(firebaseToken)
            }
        }

    

是FirebaseInstanceIdService已弃用

来自DOCS:这个类已弃用。 支持在FirebaseMessagingService中覆盖onNewToken。一旦实现了该功能,就可以安全地删除该服务。

无需使用FirebaseInstanceIdService服务获取FCM token即可安全移除FirebaseInstanceIdService服务

现在我们需要在FirebaseMessagingService中@Override onNewToken获取Token

示例代码

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String s) {
        Log.e("NEW_TOKEN", s);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Map<String, String> params = remoteMessage.getData();
        JSONObject object = new JSONObject(params);
        Log.e("JSON_OBJECT", object.toString());

        String NOTIFICATION_CHANNEL_ID = "Nilesh_channel";

        long pattern[] = {0, 1000, 500, 1000};

        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Your Notifications",
                    NotificationManager.IMPORTANCE_HIGH);

            notificationChannel.setDescription("");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setVibrationPattern(pattern);
            notificationChannel.enableVibration(true);
            mNotificationManager.createNotificationChannel(notificationChannel);
        }

        // to diaplay notification in DND Mode
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = mNotificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID);
            channel.canBypassDnd();
        }

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

        notificationBuilder.setAutoCancel(true)
                .setColor(ContextCompat.getColor(this, R.color.colorAccent))
                .setContentTitle(getString(R.string.app_name))
                .setContentText(remoteMessage.getNotification().getBody())
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setAutoCancel(true);


        mNotificationManager.notify(1000, notificationBuilder.build());
    }
}

#编辑

您需要在清单文件中注册您的FirebaseMessagingService

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

#如何在您的活动中获得令牌

.getToken ();也是不赞成的 如果你需要在你的活动中获取令牌,请使用getInstanceId ()

现在我们需要使用getInstanceId()来生成令牌

返回此Firebase项目的ID和自动生成的令牌。

这将生成一个实例ID,如果它还不存在,它会定期向Firebase后端发送信息。

返回

任务,您可以使用该任务通过包含ID和令牌的InstanceIdResult查看结果。

示例代码

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( MyActivity.this,  new OnSuccessListener<InstanceIdResult>() {
     @Override
     public void onSuccess(InstanceIdResult instanceIdResult) {
           String newToken = instanceIdResult.getToken();
           Log.e("newToken",newToken);

     }
 });

# #编辑2

下面是kotlin的工作代码

class MyFirebaseMessagingService : FirebaseMessagingService() {

    override fun onNewToken(p0: String?) {

    }

    override fun onMessageReceived(remoteMessage: RemoteMessage?) {


        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val NOTIFICATION_CHANNEL_ID = "Nilesh_channel"

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "Your Notifications", NotificationManager.IMPORTANCE_HIGH)

            notificationChannel.description = "Description"
            notificationChannel.enableLights(true)
            notificationChannel.lightColor = Color.RED
            notificationChannel.vibrationPattern = longArrayOf(0, 1000, 500, 1000)
            notificationChannel.enableVibration(true)
            notificationManager.createNotificationChannel(notificationChannel)
        }

        // to diaplay notification in DND Mode
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = notificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID)
            channel.canBypassDnd()
        }

        val notificationBuilder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)

        notificationBuilder.setAutoCancel(true)
                .setColor(ContextCompat.getColor(this, R.color.colorAccent))
                .setContentTitle(getString(R.string.app_name))
                .setContentText(remoteMessage!!.getNotification()!!.getBody())
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setAutoCancel(true)


        notificationManager.notify(1000, notificationBuilder.build())

    }
}

只需调用此方法即可获得Firebase消息传递令牌

public void getFirebaseMessagingToken ( ) {
        FirebaseMessaging.getInstance ().getToken ()
                .addOnCompleteListener ( task -> {
                    if (!task.isSuccessful ()) {
                        //Could not get FirebaseMessagingToken
                        return;
                    }
                    if (null != task.getResult ()) {
                        //Got FirebaseMessagingToken
                        String firebaseMessagingToken = Objects.requireNonNull ( task.getResult () );
                        //Use firebaseMessagingToken further
                    }
                } );
    }

在构建中添加这个依赖后,上面的代码工作得很好。gradle文件

implementation 'com.google.firebase:firebase-messaging:21.1.0'

注意:这是针对上述依赖项所做的代码修改,以解决弃用问题。(截至2021年5月9日工作代码)

在KOTLIN:-如果你想保存Token到DB或共享首选项,然后覆盖onNewToken在FirebaseMessagingService

override fun onNewToken(token: String) {
        super.onNewToken(token)
    }

在运行时获取令牌,使用

FirebaseInstanceId.getInstance().instanceId
                        .addOnSuccessListener(this@SplashActivity) { instanceIdResult ->
                            val mToken = instanceIdResult.token
                            println("printing  fcm token: $mToken")
                        }