I have a Service
that uses Handler
and Thread
to run some code every 5 seconds. When I call stopSelf()
the service seems to have stopped, because from the device Setting -> Apps -> Running it doesn't show there.
But the code inside the thread keeps on running every 5 seconds, although i have stopped the service.
Why is the Handler
and Thread
alive even when the service has stopped? How do i stop the Handler
and Thread
, when the service has stopped.
final Handler h = new Handler();
final int delay = 5000; // milliseconds
h.postDelayed(new Runnable() {
public void run() {
// do something
final SharedPreferences sharedPref = getSharedPreferences(
getString(R.string.prefs), Context.MODE_PRIVATE);
if (sharedPref != null) {
new Thread(new Runnable() {
@Override
public void run() {
// SOME CODE
Log.d("UPDATING"," something here");
isUpdated = updateToServer(data);
if(isUpdated) {
sharedPref.edit().putBoolean("updated",true).commit();
stopSelf();
}
}
}).start();
}
h.postDelayed(this, delay);
}
}, delay);