【问题标题】:Not getting refreshed token firebase android没有得到刷新令牌firebase android
【发布时间】:2017-02-16 14:23:41
【问题描述】:

我无法在 firebase 中获取刷新令牌。我已经阅读了文档并完全按照 android 的步骤进行操作。在我的日志中,我发现 firebase 连接成功。不知道为什么我没有得到实例令牌。我处于初始阶段并试图在 logcat 中获取令牌。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.project.application"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />

    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <application
        android:allowBackup="false"
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name=".ProjectName"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:icon="@drawable/icon"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Light.NoTitleBar"> 

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data
                android:name="com.google.android.gms.version"
                android:value="@integer/google_play_services_version" />
        </activity>

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

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

</manifest>

    public class MyInstanceIDListenerService  extends FirebaseInstanceIdService{    
    private static final String TAG = "MyFirebaseIIDService";
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        Log.d(TAG, "Refreshed token: " + refreshedToken);
        sendRegistrationToServer(refreshedToken);

    }

 public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // TODO(developer): Handle FCM messages here.

    Log.d(TAG, "From: " + remoteMessage.getFrom());
    String messageBody = null;

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
    }

    if (remoteMessage.getNotification() != null) {
        messageBody = remoteMessage.getNotification().getBody();
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    sendNotification(messageBody);

}
private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, SplashActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_ic_notification)
            .setContentTitle("FCM Message")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

}

【问题讨论】:

  • 令牌只生成一次。您需要清除您的应用数据以获取新的推送令牌。
  • 如果我理解正确的话,我连一次都没有。我按照 firebase andriod 中的步骤进行操作,并且期待日志中的令牌。但是我根本看不到这个 Log.d(TAG, "Refreshed token:" + refreshedToken)。我应该至少得到带有 "Refreshed token" 的日志。但是日志中没有记录。
  • 你用startService(new Intent(this, MyFirebaseMessagingService .class));启动服务吗
  • @M.WaqasPervez :不,我没有把它搞砸。它不会自动启动吗?参考这里stackoverflow.com/questions/30671345/…

标签: android firebase google-cloud-messaging firebase-cloud-messaging


【解决方案1】:

第一次安装应用时,onTokenRefresh() 方法不会触发。仅由specific scenarios触发。

要获取您的令牌,您必须在应用开始时调用 FirebaseInstanceId.getInstance().getToken()(例如在 onCreate 或其他地方)。

【讨论】:

  • 如果我在创建中获得令牌。但仍然没有从 firebase 控制台收到通知消息。
  • @jenny 你能贴出你的安卓端代码来接收消息吗?
  • 我更新了我的消息服务代码。虽然我登录了,但我仍然无法在手机上收到通知。
【解决方案2】:

来自FCMhere的github项目

文档onTokenRefresh() 内容如下:

  • InstanceID 令牌更新时调用。如果先前令牌的安全性受到损害,则可能会发生这种情况。请注意,这是在最初生成 InstanceID 令牌时调用的,因此您可以在此处检索令牌。

您必须Clear Cache 的应用程序或重新安装它才能调用此方法。

【讨论】:

    【解决方案3】:

    修改你的权限

    <permission android:name="${applicationId}.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />
    

    确保您拥有正确的 google-service.json。

    注意:令牌只生成一次。尝试清理应用数据以获取新令牌

    编辑:

    或者您可以在 Activity/Fragment 类中进行迭代以手动获取令牌

    FirebaseInstanceId iid = FirebaseInstanceId.getInstance();
    String token = iid.getToken();
    
    while(token == null){
        iid = FirebaseInstanceId.getInstance();
        token = iid.getToken();
    }
    
    Logger.info("TOKEN","==>"+token);
    

    【讨论】:

      【解决方案4】:

      每当生成新令牌时都会触发 onNewToken 回调。

      /**
       * 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.
       */
      @Override
      public void onNewToken(String token) {
          Log.d(TAG, "Refreshed token: " + token);
      
          // 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.
          sendRegistrationToServer(token);
      }
      

      要获取您的令牌,您必须拨打电话FirebaseInstanceId.getInstance().getInstanceId()

       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;
                                      }
      
                                      // Get new Instance ID token
                                      String token = task.getResult().getToken();
      
                                      // Log and toast
                                      String msg = getString(R.string.msg_token_fmt, token);
                                      Log.d(TAG, msg);
                                      Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                                  }
                              });
      

      【讨论】:

      • 您可能希望表明您的答案适用于 17.1.0 中的 FirebaseMessagingService 类
      【解决方案5】:

      尝试删除 google-services.json 文件并重新添加。

      【讨论】:

        猜你喜欢
        • 2020-11-23
        • 2018-01-31
        • 2021-02-11
        • 2015-07-03
        • 2016-10-16
        • 2016-11-21
        • 2017-07-25
        • 2017-06-30
        • 1970-01-01
        相关资源
        最近更新 更多