1

So apparently Handlers should be declared static or they could leak their outer class (and the application context along with it). This obviously limits what you can do with the Handler, and I'm wondering if what I want to do is actually possible. Take a look at this piece of code:

public class MyService extends Service {

    private int counter;

    private static final Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // Increment counter here
        }

    };

    @Override
    public void onCreate() {
        super.onCreate();
        counter = 0;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        handler.sendEmptyMessage(0);
        return Service.START_STICKY;
    }

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

}

The static handler can't hold a reference to the service, and thus a simple counter++ inside handleMessage() wouldn't work. Is there a way to check if the service is running and obtain a reference to it?

Ahmad
  • 69,608
  • 17
  • 111
  • 137
soren.qvist
  • 7,376
  • 14
  • 62
  • 91
  • 1
    see http://stackoverflow.com/questions/11407943/this-handler-class-should-be-static-or-leaks-might-occur-incominghandler – biegleux Jul 15 '12 at 16:59

1 Answers1

2

You can use WeakReference to protect your Service from leaking. But actually Handler in your code looks redundant. Both onCreate and onStartCommand are called from the UI thread so you can safely increase your counter without additional synchronization.

If you really need to access counter from different threads use AtomicInteger instead of int for it. It will be more simpler than using Handler and you will gain more performance.

Andrei Mankevich
  • 2,253
  • 16
  • 15
  • Thanks, the code I gave is sort of a simplified version of my problem. In reality, the Handler handles callbacks from a worker thread, so I do not know when the Integer should be updated, but AtomicInteger seems to elegantly solve this problem, thanks a lot. – soren.qvist Jul 15 '12 at 18:48