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
?
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" />
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With