Search code examples
androidandroid-serviceandroid-broadcastreceiver

Service onStop does not stop the service


I have an service that pings every 10 seconds every activity subscribed to it. This is my Service definition:

public class MyService extends Service {

private final static String TAG = "AccountSummaryService";
public static final String BROADCAST_ACTION = "com.mypackage.mobile";
private Handler handler = new Handler();
private final int delayedStartupTime = 1000;
private Intent intent;

@Override
public void onCreate() {
    super.onCreate();
    intent = new Intent(BROADCAST_ACTION);
}

@Override
public int onStartCommand(Intent intent, int flags,  int startId) {
    handler.postDelayed(broadcast, 1000);
    return START_STICKY;
}

private Runnable broadcast = new Runnable() {
    @Override
    public void run() {
        sendBroadcast(intent);
        handler.postDelayed(this, 10000);
    }
};

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {
    super.onDestroy();
    this.stopSelf();
    handler.removeCallbacksAndMessages(broadcast);
}

In my activity I register/start and unregister/stop the servince in my onResume/onPause methods. They are called so the following code actually gets executed:

//in the onCreate
Intent anIntent = new Intent(activity, MyService.class);

@Override
public void onResume() {
    super.onResume();
    startSummaryRefreshService();
}

@Override
public void onPause() {
    super.onPause();
    stopSummaryRefreshService();
}

private void startSummaryRefreshService() {
    activity.startService(anIntent);
    activity.registerReceiver(myReceiverObject, new IntentFilter(RefreshUIService.BROADCAST_ACTION));
}

public void stopSummaryRefreshService() {
    activity.unregisterReceiver(myReceiverObject);
    activity.stopService(anIntent);
}

The problem is that even if the stopService() gets called the service still runs and when I re-register my receiver it gets called multiple times.

Basically... I can't stop the service in anyway. I've been trying many of the StackOverflow solutions but... no way.

What do I get wrong?


Solution

  • Thanks for your answers guys. The problem was the timer. onDestroy() was correctly called but the the way I defined the cycle created an infinite loop because the runnable is an object itself, separated from the service (which is actually killed with the onDestroy(), and gets recreated every 10 seconds once started.