1

I cannot figure out where I'm going wrong. I need to get the firebase token and store it in my database and by using those tokens I need to send notifications to those devices. Below is my code. I really need some help with this.

MainActivity.java

public class MainActivity extends AppCompatActivity {



@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FirebaseInstanceId.getInstance().getToken();
    FirebaseMessaging.getInstance();


}

}

FirebaseInstanceIDService.java

public class FirebaseInstanceIDService extends 
FirebaseInstanceIdService {

@Override
public void onTokenRefresh() {

    String token = FirebaseInstanceId.getInstance().getToken();
    Log.e("Token :",token);
    registerToken(token);
}

private void registerToken(String token) {

    OkHttpClient client = new OkHttpClient();
    RequestBody body = new FormBody.Builder()
            .add("Token",token)
            .build();

    Request request = new Request.Builder()
            .url("http://localhost/notify.php")
            .post(body)
            .build();

    try {
        client.newCall(request).execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

FirebaseMessagingService.java

public class FirebaseMessagingService extends 

com.google.firebase.messaging.FirebaseMessagingService{

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    showNotification(remoteMessage.getData().get("message"));
}

private void showNotification(String message) {

    Intent i = new Intent(this,MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setAutoCancel(true)
            .setContentTitle("FCM Test")
            .setContentText(message)
            .setSmallIcon(R.drawable.gas45)
            .setContentIntent(pendingIntent);

    NotificationManager manager = (NotificationManager) 
getSystemService(NOTIFICATION_SERVICE);

    manager.notify(0,builder.build());
}


}

notify.php

<?php 
if (isset($_POST["Token"])) {

       $fcm_Token=$_POST["Token"];
       $conn = mysqli_connect("localhost","root","","fcm") or 
 die("Error connecting");
       $q="INSERT INTO users (Token) VALUES ( '$fcm_Token')"
          ."ON DUPLICATE KEY UPDATE Token = '$fcm_Token';";

  mysqli_query($conn,$q) or die(mysqli_error($conn));
  mysqli_close($conn);
}
?>
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

3 Answers3

1

onTokenRefresh() is deprecated the best way to get token is :

   FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(MainActivity.this, new OnSuccessListener<InstanceIdResult>() {
            @Override
            public void onSuccess(InstanceIdResult instanceIdResult) {
                String newToken = instanceIdResult.getToken();
                Log.e("newToken", newToken);
                SharedPreferences.Editor editor = getSharedPreferences("TOKEN_PREF", MODE_PRIVATE).edit();
                if (token!=null){
                    storetoken(newToken);
                }

            }
        });
OUBADI Ahmed
  • 132
  • 2
  • 4
0

Please change your query

   $q="INSERT INTO users (Token) VALUES ( '$fcm_Token')"
      ."ON DUPLICATE KEY UPDATE Token = '$fcm_Token';";

to this

$q="INSERT INTO users (Token) VALUES ( '".$fcm_Token."')"
          ."ON DUPLICATE KEY UPDATE Token = '".$fcm_Token."';";

I think you made mistake in PHP string appending with a variable syntax. You should append the $fcm_Token like this because you are already append the strings by using . operator.

Please try this.

Pranav MS
  • 2,235
  • 2
  • 23
  • 50
0

You can check

  1. Check your internet connection with no proxy and open internet connect
  2. Replace your google-service.json with new one you can get this in firebaseconsol
  3. Please check your device has google play service in it and it working or not , firebase not work without google play service

Check -FireBaseInstanceId service does not get registered

Did you register your Firebase service in AndroidManifiest.xml file

<!-- Firebase Notifications -->
        <service
            android:name="com.indus.corelib.notification.FirebaseMessagingService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service
            android:name="com.indus.corelib.notification.FirebaseIDService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

Please follow this step one anther example and best one Good Luck

Sushant Gosavi
  • 3,647
  • 3
  • 35
  • 55