Firebase connection check online offline status in Android - java

If user turn off both wi-fi, 3g, 4g, and so on and reverse (no internet connection). Firebase database name child connections:(true/false)
So, when internet connections, wi-fi, 3g, 4g, and so on are off or missing, the user is offline so he can't be found.
Remember the two scenarios: Before and After. If user is offline before an other user search him, then he will not displayed in the list result, if user is off-line after an other user search him, then it will display NO MORE AVAILABLE icon on the user
Kindly some one help me for this problem.

To solve this, you can create a new node in your Firebase Realtime Database to hold all online users, so when the user opens the application, you'll immediately add his id to this newly created node. Then, if you want to check if the user is online, just check if his id exists in the list.
You can also add a new property named isOnline for each user in your database and then update it accordingly.
For that, I recommend you using Firebase's built-in onDisconnect() method. It enables you to predefine an operation that will happen as soon as the client becomes disconnected.
See Firebase documentation.
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");
}
});

Though this is more than a year late, to clear up the confusion. Alex's question would like to implement a live chat scenario in which each user can view everyone's online status at their ends or on their devices.
A simple solution be to create a node where all users would inject their online status each. e.g.
//say your realtime database has the child `online_statuses`
DatabaseReference online_status_all_users = FirebaseDatabase.getInstance().getReference().child("online_statuses");
//on each user's device when connected they should indicate e.g. `linker` should tell everyone he's snooping around
online_status_all_users.child("#linker").setValue("online");
//also when he's not doing any snooping or if snooping goes bad he should also tell
online_status_all_users.child("#linker").onDisconnect().setValue("offline")
So if another user, say mario checks for linker from his end he can be sure some snooping around is still ongoing if linker is online i.e.
DatabaseReference online_status_all_users = FirebaseDatabase.getInstance().getReference().child("online_statuses");
online_status_all_users.child("#linker").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String snooping_status = dataSnapshot.getValue(String.class);
//mario should decide what to do with linker's snooping status here e.g.
if(snooping_status.contentEquals("online")){
//tell linker to stop doing sh*t
}else{
//tell linker to do a lot of sh****t
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Related

Firebase Admins SDK and App check SafetyNet

I have firebase project connected to android app, and I am using App check (SafetyNet), and it work 100% well.
Also I am using admins SDK (java) to connect and do action in the project. before using the App check every thing was working 100% well, but after enabling app check I can't access and all action fail.
so how to deal with admin SDK and app check ?
FirebaseOptions options = new FirebaseOptions.Builder().setCredentials(GoogleCredentials.fromStream(
new ClassPathResource("/myproject-firebase-adminsdk.json").getInputStream()))
.setDatabaseUrl("https://myproject-default-rtdb.firebaseio.com").build();
if (FirebaseApp.getApps().isEmpty()) {
FirebaseApp.initializeApp(options);
}
DatabaseReference ref2 = FirebaseDatabase.getInstance().getReference("/users");
ref2.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Object document = dataSnapshot.getValue();
System.out.println(document);
}
#Override
public void onCancelled(DatabaseError error) {
System.out.println(error);
}
});
Firebaser here
Apologies for the inconvenience and thank you for reporting this issue -- this is similar to a previously reported issue we've seen on Admin Node.js SDK, and we are working on releasing the fix. Please follow the GitHub thread for updates.

Firebase sync problem with Android Studio app

I have a problem with Firebase: I would like to associate an app created with Android Studio, an archive created with the room class. I followed all the instructions, inserted the .json file, inserted all dependencies in the gradle, but when I insert a new item through my app, Realtime Database doesn't update. I have updated everything, also tried with a physical device, but nothing, it doesn't work.
I followed the wizard in Android Studio but I get this error when trying to connect to Firebase:
Connection failed
Firefox cannot establish a connection with the server localhost: 56495.
The site may be unavailable or overloaded. Try again in a few moments. If no pages can be loaded, check the computer's network connection. If your computer or network is behind a firewall or proxy, make sure Firefox has permissions to access the web.
If you have Android Studio, there is a very simple way of adding Firebase Functionality without all thoses steps (it worked for me)
Go to Android Studio, then Tools > Firebase > Realtime Database
and follow the very simple steps.
It will automatically download and setup everything you need automatically, you only have to log into Firebase when asked.
Then you can upload something with following code:
DatabaseReference myRef = database.getReference("/your_path/your_key");
myRef.setValue("your_value")
And if you want to get the updates in your app then following will do:
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
// This will get called every time /your_path/your_key gets
// changed so essetially every time you change your_value
// do something. Here an example of how to get a String
String str = snapshot.getValue(String.class);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});

How to implement a seen feature in Android using firebase database [duplicate]

For the past few days i've been trying to show the online/offline status of a user.. For this i have a register activity where they register and their info gets saved in firebase and if they exit an activity i have overriden its onstop method and made the value to set to offline... but if the user suddenly loses internet connection it still shows online.. i cant change it to offline because internet is needed to make a change in the database and the use doesn't have internet... SO how do i set the database value to offline... i googled quite some stuff about this but didnt find anything... Can anyone please help me out please
My code
#Override
protected void onStart() {
super.onStart();
fetchData();
// mDatabaseReference.child("UserData").child(UID).child("Online").setValue("True");
}
#Override
protected void onStop() {
super.onStop();
fetchData();
// mDatabaseReference.child("UserData").child(UID).child("Online").setValue(false);
}
What you're trying to do is known as a presence system. The Firebase Database has a special API to allow this: onDisconnect(). When you attach a handler to onDisconnect(), the write operation you specify will be executed on the server when that server detects that the client has disconnected.
From the documentation on managing presence:
Here is a simple example of writing data upon disconnection by using the onDisconnect primitive:
DatabaseRef presenceRef = FirebaseDatabase.getInstance().getReference("disconnectmessage");
// Write a string when this client loses connection
presenceRef.onDisconnect().setValue("I disconnected!");
In your case this could be as simple as:
protected void onStart() {
super.onStart();
fetchData();
DatabaseReference onlineRef = mDatabaseReference.child("UserData").child(UID).child("Online");
onlineRef.setValue("True");
onlineRef.onDisconnect().setValue("False");
}
Note that this will work in simple cases, but will start to have problems for example when your connection toggles rapidly. In that case it may take the server longer to detect that the client disappears (since this may depends on the socket timing out) than it takes the client to reconnect, resulting in an invalid False.
To handle these situations better, check out the sample presence system in the documentation, which has more elaborate handling of edge cases.

I want to Maintain User Presence in Firestore or Firebase of one device from multiple devices who accesses the single user credentials

I want to maintain user presence in Firestore or Firebase. Actually the single user account handled by multiple mobiles devices and one tablet and that tablet maintain or do actions or provide functionality against my firestore data change. so i need to maintain presence of tablet in Firestore or Firebase so other mobile device understand the tablet working or not.
So please give me some solution on that.
I use Firebase node to check connection status. code below but i not give the proper response e.g when i remove the lan cable from router then also onDataChange not fire.for disconnection.
final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myConnectionsRef = database.getReference(FirebaseAuth.getInstance().getCurrentUser().getUid()+"/tab/connections");
// stores the timestamp of my last disconnect (the last time I was seen online)
final DatabaseReference lastOnlineRef = database.getReference(FirebaseAuth.getInstance().getCurrentUser().getUid()+"/tab/lastOnline");
final DatabaseReference connectedRef = database.getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
DatabaseReference con = myConnectionsRef.push();
// when this device disconnects, remove it
con.onDisconnect().removeValue();
// when I disconnect, update the last time I was seen online
lastOnlineRef.onDisconnect().setValue(ServerValue.TIMESTAMP);
long timestamp = Calendar.getInstance().getTimeInMillis();
// add this device to my connections list
// this value could contain info about the device or a timestamp too
con.setValue(Boolean.TRUE);
}else {
long timestamp2 = Calendar.getInstance().getTimeInMillis();
}
}
#Override
public void onCancelled(DatabaseError error) {
System.err.println("Listener was cancelled at .info/connected");
}
});
Even if you are using the Firebase Realtime database or the new Cloud Firestore, what you are doing in your code is called a 1:1 relation between a user and a connection. You are looking for a user that may be connected from multiple devices. If you are using a flag that can hold a value of true or false depending on the connection status, you'll have a problem, which is if the user will disconnect from one of those devices, the onDisconnect() method from that particular device is called and will set online to false while the users may still be connected on another devices.
In my opinion, you should not rely on having a 1:1 relation between a user and their connection(s). The example in the official documentation treat connections as a collection and assume that the user is connected as long as there is any "connect Id" (generated by push()) method left for that user. I recommend you do the same thing, to prevent hard to debug race conditions and connection problems
You can update connected flag with device id on firebase realtime database, After login .
So all other devices will know about other devices.
While logout / on application Close, Make that flag to false.

How to maintain the presence status of user in firebase Android

I am developing a chat app in which i have to maintain the user online status and the technology i am using is firebase so how can i do that any kind of help is appreciated. Thanks in advance...
Mabz has the right idea conceptually, but I want to highlight a feature of Firebase that specifically addresses your use case.
The trouble that I had run into was updating the RealtimeDatabase with an 'Offline' status. That is, If the client (e.g. your Android app) is offline, how is it supposed to tell the database?
The Solution: Use DatabaseRef.onDisconnect() to set offline status automatically
DatabaseRef presenceRef =
FirebaseDatabase.getInstance().getReference("disconnectmessage");
// Write a string when this client loses connection
presenceRef.onDisconnect().setValue("I disconnected!");
From the documentation:
When you establish an onDisconnect() operation, the operation lives on
the Firebase Realtime Database server. The server checks security to
make sure the user can perform the write event requested, and informs
the your app if it is invalid. The server then monitors the
connection. If at any point the connection times out, or is actively
closed by the Realtime Database client, the server checks security a
second time (to make sure the operation is still valid) and then
invokes the event.
A (slightly) more practical example might do something like this when your app first connects:
DatabaseRef userStatus =
FirebaseDatabase.getInstance().getReference("users/<user_id>/status");
userStatus.onDisconnect.setValue("offline");
userStatus.setValue("online");
NOTE: Please note the order of the last two "online" and "offline" status lines. Do not swap it, or else you might have "ghost users" in case the onDisconnect handler fails to register due to a disconnect itself. (which is actually a race condition problem)
Based upon the information you gave and not considering the performance or bandwidth constraints, here is a way on how I would solve this:
Using a service and a thread in the Real-Time Database:
Within the Real-Time Database, I would have an OnlineStatus thread, and then I would save child Key-Value pairs of User Ids and set to their Value to "Green" or "Yellow" or "Red"; this would give me the status as to whether the user is On-line or Away. So that would look like:
OnlineStatus
User1: Green
User2: Yellow
User3: Red
Create a Service that will check if:
The user is authenticated
The app is in the background
If the user is authenticated and the app is open, then write to the OnlineStatus thread Current User as a key and "Green" as a Value.
If the app is in the background and the user is authenticated, then do the same but "Yellow" is the Value.
Anything else should result in the color "Red". Also note that if the user signs-off, you may want to write "Red" during that operation.
So this allows every device to update Firebase Real-time Database. What remains is adding a reference to your OnlineStatus location to listen to changes through a ValueEventListener.
Hope this helps.
You can use database reference listener “.info/connected” plus disconnect method dbRef.onDisconnect() to solve the presence problem of online user.
Here is some sample code:
onlineStatus = db.getReference("users/"+user.getUid()+"/onlineStatus");
connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
onlineStatus.onDisconnect().setValue("offline");
onlineStatus.setValue("Online");
} else {
onlineStatus.setValue("offline");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
You can read more in this article on my website.

Categories

Resources