Reputation: 111
I made an Android app which receives realtime data from Firebase database. In my main Activity the user has to log in with e-mail and password and by success it opens a new Activity, which receives data.
It seems to be, that when the user leaves my app, the Firebase connection is still established. That is not good for the battery.
How is the way to manage the connection for closing and reopen the app? I think I need to use onPause()
and onResume()
. I found something like goOffline()
, but I cannot found this method in the new Firebase.
Upvotes: 3
Views: 11260
Reputation: 627
I've recently added Firebase database to my App, but noticed occasionally high battery usage, and it appears to be linked to my App keeping the radio active (radio active for 1 hour 30 mins in 10 hours, but app usage approx 5 minutes).
I believe that this is linked to Firebase database as I have disabled the in-app purchase broadcast receiver which is the only other network element. I don't have any open listeners (I'm using single-value events), but some of the transactions are mutable, so it's possible one of them has failed to complete, and is regularly re-trying. Database persistence is off.
I'm currently testing the following simple addition to pause/resume (got to get some code in the answer :-) ) :
@Override
protected void onResume()
{
super.onResume();
if (FirebaseDatabase.getInstance() != null)
{
FirebaseDatabase.getInstance().goOnline();
}
}
@Override
public void onPause() {
super.onPause();
if(FirebaseDatabase.getInstance()!=null)
{
FirebaseDatabase.getInstance().goOffline();
}
}
And so far, so good. ** The main thing to note is switching activities, requires you to have this in every app that uses Firebase (I had a sign-in activity which stopped functioning as it was reading the username from the database) **
5/12/16 - update after a couple of weeks of testing. The high battery use returned yesterday. I'm testing primarily on Lollipop, and there's loads of complaints about the radio being left open for other apps. Others testing my App on Android M don't report any problems, so it's possibly a Lollipop issue. I'm going to continue to test, this time trying to remove unnecessary transactions to see if this helps... Hope this helps someone.
Upvotes: 0
Reputation: 38299
An alternative to using the goOffline()
and goOnLine()
methods is to remove ValueEventListeners
and ChildEventListeners
when they are no longer needed. My experience (with SDK 3.X only) is that Firebase will automatically disconnect after about 1 minute when then are no listeners registered and no other reason to be connected, such as a pending write.
Upvotes: 0
Reputation: 606
Yes, you may use the activity lifecycle methods like onPause()
, onStop()
on onDestroy()
to close your connection.
Also, it seems Firebase still has a goOffline()
method - https://www.firebase.com/docs/android/api/#firebase_goOffline.
Upvotes: 2