Local
Services
Local services vs. Remote Services
Local services are used by components in the same process (or VM?)
Remote services are accessible to other processes.
The interface for remote services is more complicated than for local services
Examples
Audio player
The GUI is an activity
The player is a local service that keeps on running although the GUI is no longer running (e.g., the GUI is not in focus or was closed)
Map tracker: something that marks your path on a map
The gui is an activity
Recording the locations is in a local service, so that the path is kept p to date even though the activity is no longer running
Fancy location provider: something that is better than the GPS based location provider built into the android
This should be a remote service so that different applications can use it. If it was a local service, then each app would have to have its own copy
Local service (video)
There are two parts, the service and the activity that uses the service
Start a new project called FunWithLocalServices as usual
Add a new class MyService, but derive it from android.app.Service
MyService
Add:
@Override
public void onCreate() {
super.onCreate();
Log.d("MyService","Created");
}
Add:
@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyService","Destroyed");
}
In manifest, add <service android:name=".MyService"></service>
FunWithLocalServices
In onCreate add:
Log.d(FunWithLocalServices","Starting Service");
startService(new Intent(this, MyService.class));
MyService (video)
Add:
int val = 0; // this could be anything, a function whatever
We want to provide access to MyServices member variables and functions. A binder will do this:
private final Binder binder = new LocalBinder();
public class LocalBinder extends Binder {
MyService getService() {
Log.d("MyService","localbinder");
return MyService.this;
}
}
Make onBind() return binder
Save
FunWithLocalServices
Add variable:
private MyService myService = null;
And
private ServiceConnection connectionToMyService = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder rawBinder) {
myService = ((MyService.LocalBinder)rawBinder).getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
myService = null;
}
};
In onCreate add:
bindService(new Intent(this, MyService.class), connectionToMyService, BIND_AUTO_CREATE);
At the end of onDestroy add:
unbindService(connectionToMyService);
FunWithLocalServices continued
The myService variable provides access to MyServices. Lets use it
Add button and button listener:
Button button = (Button)findViewById(R.id.Button01);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("MyLocalSERVICE","val="+myService.cnt); }
});
Note: we cannot get access to myService in onCreate (which is where Bind is called). So we use the button press.