7

I saw this sample on how to bind a service and call its methods from an Activity.

http://developer.android.com/reference/android/app/Service.html#LocalServiceSample

But I want to bind a service and call its methods from a non-Activity class.

how can I do this?

as i don't have implementation of the following methods:

bindService, unbindService

Elad Benda
  • 35,076
  • 87
  • 265
  • 471
  • 1
    you only need a context to bind to a service. the context can be an activity, a service, or an application. – njzk2 Aug 21 '13 at 12:35
  • i don't have implementation of the following methods: bindService, unbindService – Elad Benda Aug 21 '13 at 12:50
  • 1
    bindService is a method of Context. you need a context to use bindService – njzk2 Aug 21 '13 at 13:36
  • I understand. What is the adivsed workaround? creating a dummy context member? getting the application's context? – Elad Benda Aug 21 '13 at 20:45
  • 1
    Your class needs to extend `android.content.ContextWrapper` class, in which `bindService`, `unbindService` and `startService` methods are implemented, and then can use them from your extending class. – Eido95 Sep 20 '17 at 13:20

1 Answers1

4

By the same way like from Activity just take/pass instance of content Activity

Lets say you have MyActivity class and OtherClass class

so you run in OtherClass

 public class OtherClass {

    Context mContext;

    public void init(Context context){
      mContext = context;
    }
    ...

mContext.startService(new Intent(mContext, SomeService.class)); 

[EDIT]

In your case:

Intent intent = new Intent(mContext, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

See documentation here

Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225