How to Call Methods of a Service from Activity

How to call methods of a Service from activity?

One way to do this is by defining an interface with Android's AIDL and making use of the Binder subsystem to perform IPC. There is a great set of instructions at the link I posted. I'd start there and then post here if you have questions. Despite being a pretty complex topic (IPC) Android and the Binder do a really good job of making it pretty dead simple (at least to get started, I'm sure you could make it complicated if you wanted to ;-) )

Edit As pointed out in the comments, this is unnecessary if the Service and the client are running in the same process. Unless you specify otherwise, this is the default. However, it still works regardless, it just adds a bit more complexity.

Android call method in Service from Activity

A simpke way is to send an intent from Activity and handle it in onStartCommand() method of Service. Don't forget to supply intent with right action/extras & check that in onStartCommand()

EDIT:

Activity:

Add a private class:

    private class CustomReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_CUSTOM_ACTION)) {
doCustomAction();
}
}
}

Add a private field:

private CustomReceiver mCustomReceiver;

In onCreate() method:

mCustomReceiver = new CustomReceiver();

In onResume() or other lifecycle method:

IntentFilter filter = new IntentFilter(ACTION_CUSTOM_ACTION);   
registerReceiver(mCustomReceiver , filter);

In onPause() or other paired(to previous step) lifecycle method

unregisterReceiver(mCustomReceiver );

In activity whenever you wish to call use Service methods:

startService(new Intent(SOME_ACTION));

In Service:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

if (intent == null) {
return START_STICKY;
}

String action = intent.getAction();

if (action == null) {
return START_STICKY;
} else if (action.equals(SOME_ACTION)) {
invokeSomeServiceMethod();// here you invoke service method
}

return START_STICKY;
}

Note, that START_STICKY may be not the best choice for you, read about modes in documentation.

Then, when you want to notify activity that you've finished, call:

startActivity(ACTION_CUSTOM_ACTION);

This will trigger broadcast reciever where you can handle finish event.

Seems that that's a lot of code, but really nothing difficult.

Call service method from activity

You can call startService(someIntent);

For example from an activity you can do something like this

Intent serviceIntent = new Intent(this, TheService.class);
serviceIntent.addCategory("some_unique_string");
startService(serviceIntent);

Then in the service

public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
if (intent.hasCategory("some_unique_string")) {
theMethodYouWantToCall();
} else if (intent.hasCategory("some_other_string")) {
someOtherMethod();
}
}

return START_STICKY;
}

You can call startService as often as you like.

The basic idea is to create an intent that represents the "intended" method you want to call , then in the service onStartCommand method, figure out what method you should call based on the information you pass in via the intent and then call the method.

Note: You must check that the intent is not null. If the system ever kills and restarts your service, it will do so effectively calling startService with a null for the intent, so if you leave that part out you will at some point get NPE crash.

How to call a method in activity from a service

I would register a BroadcastReceiver in the Activity and send an Intent to it from the service.
See this tutorial: http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html
It might look a bit long but you'll want to learn how to use those anyway ;)

Calling activity class method from Service class

Define an interface your Service will use to communicate events:

public interface ServiceCallbacks {
void doSomething();
}

Write your Service class. Your Activity will bind to this service, so follow the sample shown here. In addition, we will add a method to set the ServiceCallbacks.

public class MyService extends Service {
// Binder given to clients
private final IBinder binder = new LocalBinder();
// Registered callbacks
private ServiceCallbacks serviceCallbacks;

// Class used for the client Binder.
public class LocalBinder extends Binder {
MyService getService() {
// Return this instance of MyService so clients can call public methods
return MyService.this;
}
}

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

public void setCallbacks(ServiceCallbacks callbacks) {
serviceCallbacks = callbacks;
}
}

Write your Activity class following the same guide, but also make it implement your ServiceCallbacks interface. When you bind/unbind from the Service, you will register/unregister it by calling setCallbacks on the Service.

public class MyActivity extends Activity implements ServiceCallbacks {
private MyService myService;
private boolean bound = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
}

@Override
protected void onStart() {
super.onStart();
// bind to Service
Intent intent = new Intent(this, MyService.class);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
super.onStop();
// Unbind from service
if (bound) {
myService.setCallbacks(null); // unregister
unbindService(serviceConnection);
bound = false;
}
}

/** Callbacks for service binding, passed to bindService() */
private ServiceConnection serviceConnection = new ServiceConnection() {

@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// cast the IBinder and get MyService instance
LocalBinder binder = (LocalBinder) service;
myService = binder.getService();
bound = true;
myService.setCallbacks(MyActivity.this); // register
}

@Override
public void onServiceDisconnected(ComponentName arg0) {
bound = false;
}
};

/* Defined by ServiceCallbacks interface */
@Override
public void doSomething() {
...
}
}

Now when your service wants to communicate back to the activity, just call one of the interface methods from earlier. Inside your service:

if (serviceCallbacks != null) { 
serviceCallbacks.doSomething();
}

Android - Using method from a Service in an Activity?

You have to expose service`s switchSpeaker method for clients. Define your .aidl file. Than bind to that service from your activity and simply call switchSpeaker.
See documentation

No other simple way to call this method, only if it static)

Call method in a running activity from a service

write this code in application class

 public Context currentactvity = null;
public Context getCurrentactvity() {
return currentactvity;
}

public void setCurrentactvity(Context currentactvity) {
this.currentactvity = currentactvity;
}

write this code in each activity onresume method and in onpause method set null

 // in onresume
MyApplication.getInstance().setCurrentactvity(this);

// in onpause
MyApplication.getInstance().setCurrentactvity(null);

now you can call activity method from service class

  if (MyApplication.getInstance().getCurrentactvity() != null && MyApplication.getInstance().getCurrentactvity() instanceof youractivityname) {
((youractivityname) MyApplication.getInstance().getCurrentactvity()).youmethodname(parameter);

}

Call service methods from activity without binding

add an action you use to call startService, one for every different method/case you want to call/handle, and retrieve it with intent.getAction(), when onStartCommand is called

From the documentation of startService

Every call to this method will result in a corresponding call to the
target service's onStartCommand(Intent, int, int) method, with the
intent given here. This provides a convenient way to submit jobs to a
service without having to bind and call on to its interface.



Related Topics



Leave a reply



Submit