Service and Activity
I have a service GPS.java and an activity message.java which is bound to the mentioned service(开发者_Go百科GPS.java). I have bounded them using binder and service connection. I want the values of my activity class which i have sent using putExtra(Sring,value). How would i receive them in my service?
If you supplied the values in the intent when you launched/binded to the service you can access the data from Intent.getExtras
However, if you're using a binder you need to create a method for giving the service values as the intent received in onBind
will not contain any extras.
Here is an example:
In the service:
private final ExampleBinder binder = new ExampleBinder();
private class ExampleBinder extends Binder {
public void setExtras(Bundle b) {
// Set extras and process them
}
public ExampleService getService() {
return ExampleService.this;
}
public void registerClient(ClientInterface client) {
synchronized(clients) {
clients.add(client);
}
}
public void unregisterClient(ClientInterface client) {
synchronized(clients) {
clients.remove(client);
}
}
};
public IBinder onBind(Intent intent) {
return binder;
}
private final HashSet<ClientInterface> clients = new HashSet<ClientInterface>();
public static interface ClientInterface {
int value1();
String value2();
}
In the client:
public class ExampleActivity extends Activity implements ExampleService.ClientInterface {
private final ServiceConnection connection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
// Handle unexpected disconnects (crashes)
}
public void onServiceConnected(ComponentName name, IBinder service) {
ExampleService.ExampleBinder binder = (ExampleService.ExampleBinder) service;
binder.registerClient(ExampleActivity.this);
}
};
public void onResume() {
bindService(new Intent(this, ExampleService.class), connection, Context.BIND_AUTO_CREATE);
}
public void onPause() {
unbindService(connection);
}
public int value1() {
return 4711;
}
public String value2() {
return "foobar";
}
I can add that this is all assuming you're not using AIDL, if you are the solution is quite similar, just add an extra method in your interface declaration.
You should read more about bound services here: http://developer.android.com/guide/topics/fundamentals/bound-services.html or see an example: http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
There is also an example included in the SDK called LocationService.java
精彩评论