0

Actually I want to show users online/offline status. I read https://firebase.google.com/docs/firestore/solutions/presence and implemented onDiscount() to update Realtime Database that isOnline = false on discount but the problem is this data does not update inside Firestore when the user is discount.

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


     Map<String, Object> user = new HashMap<>();


        myRef.child(IS_ONLINE).setValue(true);
        myRef.child(IS_ONLINE).onDisconnect().setValue(false);

        myRef.child("isOnline").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                status = snapshot.getValue(Boolean.class);
                user.put("isOnline", status);
                doctRef.set(user);

            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });


}
Shoaib Kakal
  • 1,090
  • 2
  • 16
  • 32

1 Answers1

2

I created a service to call this method, you can try like this. Once the apps is really removed from the background, this service will trigger.

public class ClosingService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        // Handle application closing
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child(getString(R.string.USER));
        FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        if (firebaseUser != null) { databaseReference.child(firebaseUser.getUid()).child(getString(R.string.sedang_online)).setValue(false);
        databaseReference.child(firebaseUser.getUid()).child(getString(R.string.lastSeen)).setValue(System.currentTimeMillis());
    }
    // Destroy the service
    stopSelf();
}
}

After that, this service is called when the apps is started. For example, at Splashscreen activity.

    //Start closing service
    final Intent stickyService = new Intent(this, ClosingService.class);
    startService(stickyService);

And don't forget to create the service at androidmanifest.

   <service
        android:name=".u.ClosingService"
        android:stopWithTask="false" />
Ticherhaz FreePalestine
  • 2,738
  • 4
  • 20
  • 46