Search code examples
javaandroidfirebase-realtime-databaseandroid-service

how to stop Services which detect changes in firebase realtime database


I want to retrieve data continuously from firebase realtime database. I have made a service for that purpose but, the service do not stops on calling stopService. I want to stop service when i got the appropriate data. Please help.

I tried

Intent intent = new Intent(MainActivity.this,BackgroundSoundService.class);  
stopService(intent);

But this didn't not work. What else i need to do to stop this service?

 @Override
public int onStartCommand(Intent intent, int flags, int startId) {
   IniTializeSpeech(getApplicationContext());
    mDatabase = FirebaseDatabase.getInstance().getReference();
    mDatabase.child("objectsData").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
           String ss =(String) dataSnapshot.getValue();
           Log.i("OnDataChange",ss);
            t1.speak(dataSnapshot.getValue().toString(), TextToSpeech.QUEUE_FLUSH, null);
        }

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

        }
    });
    return Service.START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
}

Solution

  • If you're only interested in getting the data once, you can instead use addListenerForSingleValueEvent:

    mDatabase.child("objectsData").addListenerForSingleValueEvent(...
    

    If you have a more complex condition, you can use your current code to register. But to later stop the event listener from responding to data changes, you need to remove that listener.

    To do this, you first keep a reference to the listener when you register it:

    ValueEventListener myListener = mDatabase.child("objectsData").addValueEventListener(...
    

    And then you can later remove it with:

    mDatabase.child("objectsData").removeEventListener(myListener)