希望你们所有人都知道这个类,用来获取通知令牌,每当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);
}

当前回答

更新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())

    }
}

其他回答

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

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

首先导入com.google.firebase.messaging.FirebaseMessaging; 然后 只需使用firebasemessage . getinstance ().getToken().getResult();而不是FirebaseInstanceId.getInstance().getToken().getresult()

就是这样。

这:

FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken()

假定为已弃用的解决方案:

FirebaseInstanceId.getInstance().getToken()

EDIT

.getToken .getResult .getInstanceId FirebaseInstanceId.getInstance () () () () 如果任务还没有完成,可以产生异常,所以Nilesh Rathod描述的方法(使用. addonsuccesslistener)是正确的方法。

科特林:

FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(this) { instanceIdResult ->
        val newToken = instanceIdResult.token
        Log.e("newToken", newToken)
    }

更新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())

    }
}

你可以使用服务

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

public class MyFirebaseMessagingService extends FirebaseMessagingService{
           @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.e("NEW_TOKEN = = == = = =",s);
    }

}

如果你想在活动中使用

FirebaseMessaging.getInstance ().getToken ().addOnCompleteListener ( task -> {
                Log.e("spalsh",task.getResult());
                    });