Search code examples
javaandroidandroid-serviceandroid-binder

Service Connection Leak in android app when back to a previous page


Hello i am developing a clock in and out attendance app which has a timer service that runs when the user clocks in. the issue i am having is when i start the service and then press the back button on the phone to return to the previous page i get a service connection leak and i am not sure how to resolve this as it seems to stop the service.

//onStart - to start the timer in service class

     public int onStartCommand(Intent intent, int flags, int startId) {
            manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
            displayNotification("Clock in timer started");
            clockTask = new TimerTask() {
                public void run() {
                    seconds++;
                }
            };
            startCounter();

            return START_STICKY;
        }

//onDestroy to stop the service and counter
 public void onDestroy() {
        super.onDestroy();
        long mins = seconds/60;
        seconds%=60;
        long hours = mins/60;
        mins%=60;
        stopCounter();
        // manager.cancel(R.string.notification);
        displayNotification("Clocked out after : "+""+hours+":"+mins+":"+String.format("%02d",seconds));
        //seconds = 0L;
    }

//how i bind the intent in my activity class

   Intent i = new Intent(this, StartTimerService.class);
        bindService(i, seamysConnection, Context.BIND_AUTO_CREATE);

enter image description here

Any help would be greatly appreciated


Solution

  • that happens when Android OS destroys Activity and finds that A ServiceConnection still binded to a running Service, so you need to Unbind the service before destroying your Activity (back to a previous page )

    unbind the server

    unbindService(seamysConnection);
    

    Note:

    You should use same context for binding a service and unbinding a service. If you are binding Service with getApplicationContext() so you should also use getApplicationContext.unbindService(..)