Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 228
Robin Dijkhof Avatar asked May 06 '17 11:05

Robin Dijkhof


2 Answers

Try delegating to an intent service like this

public class AuthenticationCheckService extends IntentService {

public AuthenticationCheckService() {
    super("AuthenticationCheckService");
}

@Override
protected void onHandleIntent(@Nullable Intent intent) {
    //Once this code runs and its done the service stops so need to worry about long running service
    checkAuthenticationStatus();
}

private void checkAuthenticationStatus() {
    FirebaseAuth.getInstance().addAuthStateListener(new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth)  {
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null) {
            //Do stuffs
        } else {
            //Resolve to authentication activity
        }
    }
});
}
}

Then start the service inside the onReceive method like this

@Override
public void onReceive(final Context context, Intent intent) { 
 //Method implemented below  
 checkAuthStatus(context);

}

private void checkAuthStatus(Context context) {
    Intent authCheckIntent = new Intent(context, AuthenticationCheckService.class);
    context.startService(authCheckIntent);
}

then remember to register the service in your manifest file

 <service android:name=".AuthenticationCheckService" />
like image 86
Wan Clem Avatar answered Sep 18 '22 16:09

Wan Clem


BroadcastReceiver aren't meant to be used for long-running operations, try starting IntentService from that receiver instead. Android will finish this receiver if work takes too long. Maybe, that is the reason why the result is null sometimes.

like image 44
Alex Shutov Avatar answered Sep 19 '22 16:09

Alex Shutov