Download presentation
Presentation is loading. Please wait.
1
Service Services
2
Types of Services Started Services Bound Services As Both
If it is started by calling startService(); Can run indefinitely in the background Used for performing one operation with no returned result Bound Services It is started by calling bindService() Provide services as a server to clients or Provide message passing Destroyed when no client is bound to it As Both A service may are started by calling startService() and bound by calling bindService() as long as it implements onStartCommand() and OnBind()
3
The Basics - 1 A service must extends Service
A service must be declared in Manifest.xml Must override: onStartCommand() Android calls this when startService() is called You are responsible for stopping the service by calling stopSelf() or stopService() onBind() Android calls this when bindService() is called Returns an IBinder for service onCreate() Android calls this as one-time setup when it is first created Android calls this before onStartCommand() and onBind() onDestory() Android calls this when service is no longer used Use this to clear up resources such as threads, listeners, etc
4
The Basics - 2 Declaring in manifest.xml
<application …> <service android:name=“.MyService” /> </application> </manifest> You can make your service private and public android:exported=“true” or “false” ANR – Application Not Responding Service is run in the main thread of its hosting process by default. So if it contains CPU intensive work, a thread should be deployed for the job.
5
Service Lifecycle Callbacks
public class ExampleService extends Service { public void onCreate() { // The service is being created } public int onStartCommand(Intent intent, int flags, int startId) { // The service is starting, due to a call to startService() return mStartMode; } public IBinder onBind(Intent intent) { // A client is binding to the service with bindService() return mBinder; } public boolean onUnbind(Intent intent) { // All clients have unbound with unbindService() return mAllowRebind; } public void onRebind(Intent intent) { // A client is binding to the service with bindService(), // after onUnbind() has already been called } public void onDestroy() { // The service is no longer used and is being destroyed } }
6
Service Lifecycle
7
Started Services Service IntentService The base class of all services
By default code is executed in the main thread IntentService A subclass of Service A worker thread handles all start requests Default onStartCommand() queues up all requests Default onBind() returns null Start requests are handled in a sequential manner Implement onHandleIntent() to handle requests
8
Using IntentService The Service The Calling Component
class MyService extends Intent Service { // must implement constructor can call super with a name public MyService() { super(“my service”); public void onHandleIntent(Intent intent) { String data = intent.getStringExtra(“SOME_DATA”); // process data } The Calling Component class MyActivity extends Activity { Intent mIntent; public void onCreate(…) { // normal work of onCreate public void callService(String data) { mIntent = new Intent(this, MyService.class); mIntent.putExtra(“SOME_DATA”, data); startService(mIntent); public void onDestroy() { super.onStop(); if (mIntent != null) { stopService(mIntent); mIntent = null;
9
Using Service - 1 Manifest.xml
<application …. <service android:name=".SimpleStartedService" /> </application> The Service public class SimpleStartedService extends Service { // 1. implement the following to handle request public int onStartCommand(Intent intent, int flags, int startId) { String message = intent.getStringExtra("SERVICE_DATA"); if (message != null) toast("MSG: " + message); else toast("MSG: No message received");; // 2. if the service is killed by system, don’t re-create return START_NOT_STICKY; } public void onDestroy() { toast("Service Destroyed"); super.onDestroy();
10
Using Service - 2 The Calling Component
public class MainActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void startAService(View view) { String message = mEditText.getText().toString(); // 1. create an intent and start service mIntent = new Intent(this, SimpleStartedService.class); mIntent.putExtra("SERVICE_DATA", message); startService(mIntent); mTextView.setText("Service Started"); public void onDestroy() { // 2. Destory service when not needed stopService(mIntent); super.onDestroy();
11
onStartCommand(): int
The returned value determines what should happen if the service is killed. START_NOT_STICKY do not recreate the service Safest: no running service when not needed. START_STICKY Recreate the service and call onStartCommand(), but do not redeliver the last intent. Instead, the system calls onStartCommand() with a null intent. Suitable for: services running indefinitely and waiting for a job such as media players START_REDELIVER_INTENT Recreate the service and call onStartCommand() with the last intent that was delivered to the service. Suitable for: services that are actively performing a job that should be immediately resumed, such as downloading a file. In all of the cases, if there are pending intents, they will be delivered one by one.
12
Bound Service: Basics The Service The Clients Subclass Service
Write all the functions the service provides Subclass Binder which returns a service object to the client Override onBinder() to return the service object In OnDestroy() release all the resources such as threads. The Clients Subclass ServiceConnection for a connection listener Call bindService and pass the connection listener Call functions provided by the service Call unbindService() to unbind the connection
13
Bound Service: The Server
public class LocalService extends Service { // Binder given to clients private final IBinder mBinder = new LocalBinder(); // 1. return an obj for the client to get a reference to the public IBinder onBind(Intent intent) { return mBinder; } // 2. all the public methods the client can call public int getRandomNumber() { return new Random().nextInt(100); } // 3. Your Binder which returns a reference to the server public class LocalBinder extends Binder { LocalService getService() { // Return this instance of LocalService return LocalService.this; } } }
14
Bound Service: The Client 1
public class BindingActivity extends Activity { LocalService mService; // reference to the server boolean mBound = false; // if the server is connected // 1. bind the service in onStart() protected void onStart() { super.onStart(); // Bind to LocalService Intent intent = new Intent(this, LocalService.class); // mConnection contains callbacks when connected bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } // 2. unbind the service onStop() protected void onStop() { super.onStop(); if (mBound) { unbindService(mConnection); mBound = false; } } // 3. call the methods of the server public void onButtonClick(View v) { if (mBound) { int num = mService.getRandomNumber(); Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show(); } }
15
Bound Service: The Client 2
// 4. Defines callbacks for service binding private ServiceConnection mConnection = new ServiceConnection() { // called when service is connected public void onServiceConnected(ComponentName className, IBinder service) { // get a reference to the server LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } // called when service is disconnected public void onServiceDisconnected(ComponentName arg0) { mBound = false; } }; ...
16
Using Messenger The client (activity) and the service exchanges Messages Message can contain simple data, object, and a Bundle
17
The Service Subclass Handler to receive Message through handleMessage(Message msg); class MyHandler extends Handler { public void handleMessage(Message msg) { // handle msg }} } Create a Messenger with your handler Messenger receiver = new Messenger(new MyHandler()); Return Messenger.getBinder() from Service#onBind(Intent) public IBinder onBind(Intent intent) { return receiver.getBinder(); }
18
Message – What data it can carry
“Identifier” public int what; Lower-cost data public int arg1, arg2 An arbitrary object public Object obj A Bundle to pass more data public Bundle getData() public void setData(Bundle)
19
The Client (Activity) - 1
Bind server in onStart() public void onStart() { … Intent intent = new Intent(this, BasicMessengerService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } Unbind server in onStop() public void onStop() { if (mBound) { unbindService(mConnection); mBound = false; Subclass ServiceConnection to receive messenger class MyServiceConnection implements ServiceConnection { public void onServiceConnected(ComponentName className, IBinder service) { mSendMessenger = new Messenger(service); mBound = true; public void onServiceDisconnected(ComponentName arg0) { mSendMessenger = null;
20
The Client (Activity) - 1
Get a Message object int what = 100; int arg1 = 123; int arg2 = 234; Message message = Message.obtain(null, what, arg1, arg2); Set extra data to the message message.obj = new Student(); Bundle data = new Bundle(); data.putString("NAME", "Smith"); message.setData(data); Send the message mSendMessenger.send(message);
21
Service may Reply In the client In the service
set replyTo before sending Message.replyTo = new Messenger(new MyOtherHandler()); In the service Get replyTo Messenger to send reply void handleMessage(Message msg) { ... msg.replyTo.send(Message.obtain(null, WHAT, ARG1, ARG2)); }
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.