如何在android中获取有效的firebase令牌?

时间:2017-08-06 17:16:32

标签: android firebase firebase-cloud-messaging

我正在尝试发送推送通知,但是当代码执行时,它会显示无效的注册错误。以下是代码

LoginActivity

 String getToken = FirebaseInstanceIDService.onTokenRefreshs();
String getUsername = username.getText().toString();
String URL = DataHolder.TokenUrl(getUsername,getToken);

OnTokenRefresh代码

public class FirebaseInstanceIDService extends FirebaseInstanceIdService {
    public static String onTokenRefreshs(){
        String token = FirebaseInstanceId.getInstance().getToken();
        return  token;
    }
}

推送通知代码

$url = 'https://fcm.googleapis.com/fcm/send';

          $message = array("message" => "hell man");

     $xyz=array("firebasetokengoeshere I haven't included for now");
     $fields = array(
     'to' => json_encode($xyz),
     'data' => $message
     );

     $headers = array(
     'Authorization:key = Appkey goes here',
     'Content-type: application/json'
     );

     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_POST, true);
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
     $result = curl_exec($ch);
     if($result === FALSE){

     }
     curl_close($ch);

     return $result;



     $message_status = send_notification($tokens, $message);
     echo $message;
  

{ “multicast_id”:6744250798651355841, “成功”:0, “失败”:1, “canonical_ids”:0 “结果”:[{ “错误”: “InvalidRegistration”}]}

我得到了上面的结果。如何解决此错误。

2 个答案:

答案 0 :(得分:1)

获取令牌的正确方法是:

String token = FirebaseInstanceId.getInstance().getToken();

FirebaseInstanceIdService的实现应包含onTokenRefresh()方法,只要创建新标记,该方法就会自动调用。您不需要明确地调用它。您不需要将其创建为您自己的方法,因为它被覆盖。此外,它不应该是static。它应该是这样的:

public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        // Store the token
    }
}

答案 1 :(得分:0)

你应该使用下面的代码:

public class FirebaseCloudInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "Firebase";

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

    AppPref.saveFCMToken(this, fcmToken);
}

}

通常,我会将Firebase令牌存储在我的sharedPref中。为了更方便,您可以尝试我的小型util类,它可以充当SharePref util,更方便。在此处找到android-shared-preference-util