I want to make an application in which if user is connected to internet it must show as an online user on other devices using firebase. what should be appropriate way for that ?
2 Answers
I recommend using Firebase's built-in onDisconnect()
method. It enables you to predefine an operation that will happen as soon as the client becomes disconnected.
You can also detect the connection state of the user. For many presence-related features, it is useful for your app to know when it is online or offline. Firebase Realtime Database provides a special location at /.info/connected
which is updated every time the Firebase Realtime Database client's connection state changes. Here is an example also from the official documentation:
DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
System.out.println("connected");
} else {
System.out.println("not connected");
}
}
@Override
public void onCancelled(DatabaseError error) {
System.err.println("Listener was cancelled");
}
});

- 130,605
- 17
- 163
- 193
-
1How to check other user online presence? just like whatsapp status of online/offline – androidXP Feb 17 '19 at 09:00
-
@androidXP As explained in the above answer. – Alex Mamo Feb 17 '19 at 11:03
-
Is this for only Realtime database? How to achieve this in Firestore database? – Ssubrat Rrudra Dec 09 '19 at 04:32
-
@SsubratRrudra Yes, that's only for Firebase real-time database. The second question is really a bit too broad to reasonably be able to answer in a comment. So please post another fresh question using its own [MCVE](https://stackoverflow.com/help/mcve), so I and other Firebase developers can help you. – Alex Mamo Dec 09 '19 at 07:53
You can have a list in your firebase of all online users, so when the user opens the app, you will immediately add his Id to the list. Then, if you want to check if the user is online, just check if his Id is in the list.
You can also add isOnline
variable to the user's reference in your database.

- 181
- 10
-
can i do it without opening the app ? in background when user has internet connection it should do that automatically – HAMZAA Apr 29 '18 at 22:27
-
You should use Broadcast Receiver like this https://stackoverflow.com/questions/3767591/check-intent-internet-connection. And use it inside a service – yotam ravits Apr 30 '18 at 17:24
-