0

I'm currently using FCM to trigger a SyncAdapter when there are new data for individual users.

As soon as a new user logs in into the app, I create a new account, using AccountManager, and store their auth_token, in order to be able to use it for future API calls to the server.

Now I need to send to the server not only the instanceID created by Firebase but also the user auth_token. Doing this, I'll be able to link them on the server.

This is what I was trying to do:

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();

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

        sendTokenToServer(refreshedToken);
    }

    public void sendTokenToServer(String token) {
        AccountManager accountManager = AccountManager.get(getBaseContext());
        Account[] accounts = accountManager.getAccountsByType(Constants.ACCOUNT_TYPE);

        // ...
    }
}

The issue here is that getBaseContext() is null. Given this, how do you think that I could get the account info here?

Diego Couto
  • 585
  • 1
  • 5
  • 16

1 Answers1

0

Well, actually the issue wasn't related to accessing the context from FirebaseInstanceIdService, but on how I was initially instantiating my object.

After the successful login, I was creating an async task to send the device instance ID to the server:

new SendInstanceIDTask().execute(FirebaseInstanceId.getInstance().getToken());

Doing this, I wasn't able to access the context. Changing my async task like below I could make everything work as expected:

private class SendInstanceIDTask extends AsyncTask<String, Void, Void> {
    private Context context;

    public SendInstanceIDTask(Context context) {
        this.context = context;
    }

    @Override
    protected Void doInBackground(String... params) {
        MyFirebaseInstanceIDService firebaseService = new MyFirebaseInstanceIDService();
        firebaseService.sendTokenToServer(context, params[0]);

        return null;
    }
}
Diego Couto
  • 585
  • 1
  • 5
  • 16