user10013758
user10013758

Reputation:

How to use SharedPreferences to check if the user is using an app or not?

   @Override
    public void onStart(){
    super.onStart();
    mDatabaseReference.child("Online").setValue(true);
    }

   @Override
    public void onStop(){
    super.onStop();
    mDatabaseReference.child("Online").setValue(false);
    }

My current code doesn't do the job to see if the user is online or not and people told me that i could use shared preferences for achieving the objective but i'm not sure on how to use shared preferences for editing a database value... i had only used shared preferences to check if the user had passed through an activity to skip it the next time (Signup activity and activities similar which require only one time access) Can someone please help me out on how to use shared preferences to check if the user is online or not

Upvotes: 0

Views: 108

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138824

There is no need to use SharedPreferences in such case. A simple way in which you can achieve this would be to use your Online property for each user in your database to see if it is or not online. For this, I recommend you to use 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 for presence.

You can also can 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");
        }
});

Upvotes: 1

Joy Dey
Joy Dey

Reputation: 593

You can use this code. It worked fine in my case

@Override
protected void onStart()
{
    super.onStart();

    currentUser = mAuth.getCurrentUser();

    if (currentUser == null)
    {
        LogOutUser();
    }
    else if(currentUser != null)
    {
        UsersReference.child("online").setValue("true");
    }

}

Upvotes: 1

Related Questions