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?