简体   繁体   中英

How to signal to the database that I have lost the connection - Java

How can i make that if player1 loses connection, firebase will get signal, i just need to know how to make firebase get notification that player1 lost connection for example

图片

I use this to check if there is a connection and with this you can do all this, but from here I will not be able to transfer the sign to Firebase that I have lost the connection, because in order to transfer it you need to have a connection:

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 {
                Toast.makeText(DuelGame.this, "У вас отсутствует подключение к интернету!", Toast.LENGTH_SHORT).show();
                System.out.println("not connected");
        }
    }

    @Override
    public void onCancelled(DatabaseError error) {
        System.err.println("Listener was cancelled");
    }
});

Once again I will explain more simply. I need Firebase to check if people are online or not, if not then some actions are enabled.

The code you have allows the client to detect whether it is connected to the Firebase Realtime Database backend. As you've discovered, this code does not allow you to update the database once the client disconnects - as at that point there's no way for it to write to the database anymore.

To detect such disconnect events, Firebase has onDisconnect handlers . With this, you register a write operation with the server while you are connection, which the server then executes once it detects that the client is gone.

The documentation even contains an example of a complete presence system built with .info/connected and onDisconnect . I recommend using that as the basis for your own use-case too, as it handles some edge-cases you may not immediately think of yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM