Книга: Beginning Android
Bound for Success
Bound for Success
To use a service, you first need to create an instance of your own ServiceConnection
class. ServiceConnection
, as the name suggests, represents your connection to the service for the purposes of making IPC calls. For example, here is the ServiceConnection
from the WeatherPlus
class in the WeatherPlus
project:
private ServiceConnection svcConn = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder binder) {
service = IWeather.Stub.asInterface(binder);
browser.postDelayed(new Runnable() {
public void run() {
updateForecast();
}
}, 1000);
}
public void onServiceDisconnected(ComponentName className) {
service = null;
}
};
Your ServiceConnection
subclass needs to implement two methods:
1. onServiceConnected()
, which is called once your activity is bound to the service
2. onServiceDisconnected()
, which is called if your connection ends normally, such as you unbinding your activity from the service
Each of those methods receives a ComponentName
, which simply identifies the service you connected to. More importantly, onServiceConnected()
receives an IBinder
instance, which is your gateway to the IPC interface. You will want to convert the IBinder
into an instance of your AIDL interface class, so you can use IPC as if you were calling regular methods on a regular Java class (IWeather.Stub.asInterface(binder)
).
To actually hook your activity to the service, call bindService()
on the activity:
bindService(serviceIntent, svcConn, BIND_AUTO_CREATE);
The bindService()
method takes three parameters:
1. An Intent
representing the service you wish to invoke — for your own service, it’s easiest to use an intent referencing the service class directly (new Intent(this, WeatherPlusService.class)
)
2. Your ServiceConnection
instance
3. A set of flags — most times, you will want to pass in BIND_AUTO_CREATE
, which will start up the service if it is not already running
After your bindService()
call, your onServiceConnected()
callback in the ServiceConnection
will eventually be invoked, at which time your connection is ready for use.
- Forced writes - палка о двух концах
- Forced Writes
- Chapter 15. Graphical User Interfaces for Iptables
- What NAT is used for and basic terms and expressions
- Information request
- SCTP Generic header format
- System tools used for debugging
- FORWARD chain
- How to use this License for your documents
- 1. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
- Оператор цикла foreach
- Foreword