Search code examples
androidkotlinservicehandlerrunnable

Stop Handler in service Android


I have been using handler inside service class, the handler is responsible for sending location every 5 seconds via socket. When logging out, the service gets stopped but the handler still running. I tried every possible way, By using any boolean variable is not feasible in my case because i have to start again that handler.

public Runnable mn_Runnable12 = new Runnable() {
        public void run() {
            gps = new GPSTracker(LocationService.this);
            if (gps.canGetLocation()) {
                latString = Double.toString(gps.getLatitude()); // Live
                logString = Double.toString(gps.getLongitude());
                connection= MyApplication.getInstance().getConnection();
                if (connection!=null&&connection.isConnected()) {
                    sendLocation();
                }

            }
        }
    };

this is inside onCreate() of service.

 T.scheduleAtFixedRate(new TimerTask() {
                                  @Override
                                  public void run() {
                                      mHandler12.postDelayed(mn_Runnable12, 5000);
                                  }
                              },
                5000,
                5000);

I try to stop the handler in onDestroy method of service, service gets topped but the handler still running.

 @Override
    public void onDestroy() {
        System.out.println("Location Service Detaroy-----");
        if (connection.isConnected()) {
            unSubscribe();
        }
        mHandler12.removeCallbacksAndMessages(null);
        mHandler10.removeCallbacksAndMessages(null);
    }

Solution

  • You Also have to cancel Timer Since its running repeatedly with an interval. First cancel timer and then remove handlers callback.

      T.cancel();
      T.purge();
      // remove handler here