Robin Dijkhof Robin Dijkhof - 1 year ago 78
Android Question

How to use firebase database from broadcastreceiver

I'm trying to use Firebase Database from a

BroadcastReceiver
to fetch some data. Unfortunately the user is
null
sometimes, which means I can't use the UID the fetch data.

@Override
public void onReceive(final Context context, Intent intent) {
FirebaseAuth.getInstance().addAuthStateListener(new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null){
//sometimes not null
}else{
//sometimes null
}
}
});
}


Also
FirebaseAuth.getInstance().getCurrentUser
is
null
sometimes. Also, i'm not running long time opertaion inside my
broadcastreceiver
. I'm talking about fetching a single opjes without any nodes under it.

How can I use Firebase database from a
BroadcastReceiver
?

Answer Source

I think I figured it out. The problem wasn;t the broadcastreceiver, but firebase refreshing the token. At that point the user was null. Something like this worked:

@Override
public void onReceive(final Context context, Intent intent) { 
    FirebaseAuth.getInstance().addAuthStateListener(new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if(user != null){
                    FirebaseAuth.getInstance().removeAuthStateListener(this);
                    //do stuff
                }else{
                    //do nothing
                }
            }
     });
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download