How to get a valid firebase token in android?
I am trying to send a push notification, but when the code runs, it shows invalidresgistration error. Below is the code
LoginActivity
String getToken = FirebaseInstanceIDService.onTokenRefreshs();
String getUsername = username.getText().toString();
String URL = DataHolder.TokenUrl(getUsername,getToken);
OnTokenRefresh
code
public class FirebaseInstanceIDService extends FirebaseInstanceIdService {
public static String onTokenRefreshs(){
String token = FirebaseInstanceId.getInstance().getToken();
return token;
}
}
pushnotification code
$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, "success": 0, "failure": 1, "canonical_ids": 0, "Results": [{"error": "InvalidRegistration"}]}
I am getting the result above. How to fix this error.
source to share
The correct way to get a token is:
String token = FirebaseInstanceId.getInstance().getToken();
Your implementation FirebaseInstanceIdService
should contain a method onTokenRefresh()
that gets called automatically whenever a new token is created. You don't need to call this explicitly. You don't need to create it as your own method as it is overridden. Moreover, it shouldn't be static
. It should be something like this:
public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
// Store the token
}
}
source to share
You should go to the snippet below:
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);
}
}
I usually store the Firebase token in my sharedPref. And for more convenience, you can try my little use class, which acts like SharePref for more convenience. Find it here android-shared-preference-util
source to share