-1

I've handler declared onCreate() in my service class. My app fire this handler in certain circumstances ( postDelayed method ). But if by any chance user wants to exit my application, i want that handler to stop (from being executed in X time - with removeCallBacks()). How do i get a reference to that handler object declared in service in my activity, so i can call its method? (proper way). Is that even possible?

I already checked Reference handler object from main activity, but it wasn't very helpful.

I could get a reference via static method, but is this really the proper way to do that?

Community
  • 1
  • 1
Firefoxx Pwnass
  • 135
  • 1
  • 9
  • Why don't you add a method to your Service that does that and call that method? No need to leak the handler. – Fildor Feb 07 '13 at 16:06

2 Answers2

1

If you have already have an object of the service (got through the ServiceConnection), you can expose a public method inside the Service that will call removeCallBacks on the Handler instance.

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
1

You do not need to have a handler reference in your activity, you can ask the service to stop the handler.

There are many ways to communicate with your service from the activity the easiest for your case:

1- Call startService and pass to it Intent with action e.g. stopHandler that when the service receives it calls removeCallBacks()

2- Use LocalBroadcast to send message to the service to stop the handler

You can as well bind to the service, but this will be extra work than the previous methods

Edit

In your activity you can call something like

Intent intent = new Intent(context,MyService.class);
intent.setAction("stopHandler");
startService(intent);

In your service onStartCommand or onHandleIntent depend on your service type

if(intent.getAction().equals("stopHandler")){
   // call removeCallBacks()
}

For the second solution see this

Community
  • 1
  • 1
iTech
  • 18,192
  • 4
  • 57
  • 80