Post on 16-Oct-2020
transcript
4/28/2016
1
MOBILE APPLICATION DEVELOPMENT
IMRAN IHSAN
ASSISTANT PROFESSOR
WWW.IMRANIHSAN.COM
LECTURE 10SERVICES
• A Service is an application component that runs in thebackground, not interacting with the user, for anindefinite period of time.
• Higher priority than inactive Activities, so less likely tobe killedo If killed, they can be configured to re-run
automatically (when resources available)• Each service class must have a corresponding
<service> declaration in its package'sAndroidManifest.xml
Services Android Component
4/28/2016
2
• Services can be started with Context.startService(Intent intent) and Context.bindService()
• Execute in the main thread of the application’sprocess.• CPU intensive tasks must be offloaded to
background threads using Thread or AsyncTask• Alarms can be used to fire Intents at set times. These
can start services, open Activities, or broadcast Intents
Services Android Component
Services Android Component
• StartedA service is "started" when an application component (such as an activity)
starts it by calling startService(). Once started, a service can run in the
background indefinitely, even if the component that started it is destroyed.
Usually, a started service performs a single operation and does not return a
result to the caller. For example, it might download or upload a file over the
network. When the operation is done, the service should stop itself.
• BoundA service is "bound" when an application component binds to it by calling
bindService(). A bound service offers a client-server interface that allows
components to interact with the service, send requests, get results. A bound
service runs only as long as another application component is bound to it.
Multiple components can bind to the service at once, but when all of them
unbind, the service is destroyed.
4/28/2016
3
• Client components can bind to a Service when they want to interact with itContext.bindService (Intent service,
ServiceConnection conn, int flags)• Service will be started if necessary• Service remains active as long as at least one client is
bound to it
Services Android Component
• A Service has three lifecycle methods
Services Lifecycle Android Component
1. void onCreate()
2. void onStartCommand()
3. void onDestroy()
4/28/2016
4
Creating a Service Android Component
• Called whenever the Service is started withstartServicecall• So beware: may be executed several times in
Service’s lifetime!• Controls how system will respond if Service
restarted (START_STICKY)• Run from main GUI thread, so standard pattern is
to create a new Thread from onStartCommand toperform processing and stop Service whencomplete
onStartCommand Service Events
4/28/2016
5
START_STICKY is basically the same as the previous behavior, where the service
is left "started" and will later be restarted by the system. The only difference from
previous versions of the platform is that it if it gets restarted because its process is
killed, onStartCommand() will be called on the next instance of the service with a
null Intent instead of not being called at all. Services that use this mode should
always check for this case and deal with it appropriately.
START_NOT_STICKY says that, after returning from onStartCreated(), if the
process is killed with no remaining start commands to deliver, then the service will
be stopped instead of restarted. This makes a lot more sense for services that are
intended to only run while executing commands sent to them. For example, a
service may be started every 15 minutes from an alarm to poll some network state.
If it gets killed while doing that work, it would be best to just let it be stopped and
get started the next time the alarm fires.
START_REDELIVER_INTENT is like START_NOT_STICKY, except if the service's
process is killed before it calls stopSelf() for a given intent, that intent will be re-
delivered to it until it completes (unless after some number of more tries it still can't
complete, at which point the system gives up). This is useful for services that are
receiving commands of work to do, and want to make sure they do eventually
complete the work for each command sent.
onStartCommand Service Events
• Call startService()
Starting a Service Service Events
(To use this example, would need to include a ORDER_PIZZAconstant in MyServiceclass and use an Intent Filter to registerthe Service as a provider of ORDER_PIZZA)
4/28/2016
6
• Call stopService()
Stopping a Service Service Events
• Logging service• Client Activity sends log messages to service• Service writes messages to a log console
• Music player• Client Activity tells service to play a music file• Services plays music in the background (even if
Client Activity pauses or terminates)• ID service
• Client Activity requests system-wide unique ID• Service returns ID to Client
Example Services Services
4/28/2016
7
• Service requests represented as Intents• Uses a Service subclass called IntentService• IntentService requests handled sequentially in a
single worker thread• IntentService started and stopped as needed
Logging Services Services
Logging Services (Cont.) Services
public class BGLoggingDemo extends Activity {
public void onCreate(Bundle savedInstanceState) {
…
buttonStart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(BGLoggingDemo.this, BGLoggingService.class);
intent.putExtra("course.examples.Services.Logging","Log this message");
startService(intent);
}
});
}
}
4/28/2016
8
Logging Services (Cont.) Services
public class BGLoggingService extends IntentService {
…
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_NOT_STICKY;
}
protected void onHandleIntent(Intent intent) {
// create and start new Thread to handle request
…
Log.i(TAG,arg.getCharSequenceExtra("course.examples.Services.Logging").toString());
}
...
}
Logging Services (Cont.) Services
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".BGLoggingDemo" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:enabled="true" android:name=".BGLoggingService" />
</application>
4/28/2016
9
• The LoggingService is a simplified example• It doesn’t need to be implemented as a
Service• In practice you would simply start a new
Thread to do the logging• Use Services when you want to run a
component even when a user is not interacting with the Service’s hosting application
Notes on Services Services
• Client Activity can start/stop playing music via a Service• If music is playing when client leaves the
foreground, music service will continue playing
Music Player Service Services
4/28/2016
10
Music Player Service (cont.) Services
public class MusicService extends Service {
MediaPlayer player;…
public void onCreate() {player = MediaPlayer.create(this, R.raw.braincandy);player.setLooping(false);
}
public int onStartCommand (Intent intent, int flags,int startid) {
player.start();
return START_NOT_STICKY;
}
…
}
Music Player Service (cont.) Services
public class MusicServiceDemo extends Activity {
public void onCreate(Bundle savedInstanceState) {
…
button.setOnClickListener(new OnClickListener() {
public void onClick(View src) {
…
startService(new Intent(MusicServiceDemo.this,MusicService.class));
}
});
}
}
4/28/2016
11
• Activity maintains reference to a Service • Activity can make calls on the Service just as any
other instantiated class • To support this, implement onBind for the Service
Binding Activities to Services Services
• A Service has three lifecycle methods
Binding Activities to Services Service Binding
Once Service is bound, all public methods
and properties are available through the
serviceBinderobject obtained from the
onServiceConnectedhandler
4/28/2016
12
Questions?