ondisconnect()不起作用。即使断开与Internet的连接后,firebase数据库中的用户状态仍保持为true。我希望将其更改为ServerValue.TIMESTAMP ....................... ................................................... ................................................... ........
> java
package com.example.connect;
import android.app.Application;
import androidx.annotation.NonNull;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.OkHttp3Downloader;
import com.squareup.picasso.Picasso;
public class Connect extends Application
{
private FirebaseAuth auth;
private DatabaseReference userDatabase;
@Override
public void onCreate() {
super.onCreate();
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
Picasso.Builder builder = new Picasso.Builder(this);
builder.downloader(new OkHttp3Downloader(this, Integer.MAX_VALUE));
Picasso built = builder.build();
built.setIndicatorsEnabled(true);
built.setLoggingEnabled(true);
Picasso.setSingletonInstance(built);
if(auth!=null) {
auth = FirebaseAuth.getInstance();
userDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(auth.getCurrentUser().getUid());
userDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot != null) {
userDatabase.child("online").onDisconnect().setValue(ServerValue.TIMESTAMP);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
}
答案 0 :(得分:1)
您可以使用对Firebase的自定义引用,它会告诉您用户是否已连接:
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");
}
});
https://firebase.google.com/docs/database/android/offline-capabilities#section-connection-state
请记住,如果您没有Internet访问权限,这并不意味着该用户已与服务器断开连接,则服务器保留的会话将持续很长时间,直到它打算断开该用户的连接为止。
此代码将知道用户何时断开与数据库的连接。