Service Services.

Slides:



Advertisements
Similar presentations
Services. Application component No user interface Two main uses Performing background processing Supporting remote method execution.
Advertisements

Programming with Android: Notifications, Threads, Services
Cosc 5/4730 Android Services. What is a service? From android developer web pages: Most confusion about the Service class actually revolves around what.
CSE2102 Introduction to Software Engineering Lab 2 Sept/4/2013.
Programming with Android: Activities
All About Android Introduction to Android 1. Creating a New App “These aren’t the droids we’re looking for.” Obi-wan Kenobi 1. Bring up Eclipse. 2. Click.
Lec 06 AsyncTask Local Services IntentService Broadcast Receivers.
Threads, AsyncTasks & Handlers.  Android implements Java threads & concurrency classes  Conceptual view  Parallel computations running in a process.
1 Working with the Android Services Nilanjan Banerjee Mobile Systems Programming University of Arkansas Fayetteville, AR
Programming with Android: Notifications, Threads, Services Luca Bedogni Marco Di Felice Dipartimento di Scienze dell’Informazione Università di Bologna.
Cosc 5/4730 A little on threads and Messages: Handler class.
CSE 486/586, Spring 2013 CSE 486/586 Distributed Systems Content Providers & Services.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Concurrency in Android with.
P2P communication Using the GTalk Service API. Introduction Peer-to-Peer communication highly used in mobile devices. Very efficient to when certain factors.
Android Services Mobile Application Development Selected Topics – CPIT Oct-15.
안드로이드 프로그래밍 서비스와 방송 수신자 장 원 영 실습파일 :
COMP 365 Android Development.  Perform operations in the background  Services do not have a user interface (UI)  Can run without appearing on screen.
로봇 모니터링 2/2 UNIT 21 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Broadcasting Service 2.
16 Services and Broadcast Receivers CSNB544 Mobile Application Development Thanks to Utexas Austin.
1 Announcements Homework #2 due Feb 7 at 1:30pm Submit the entire Eclipse project in Blackboard Please fill out the when2meets when your Project Manager.
CSE 486/586, Spring 2012 CSE 486/586 Distributed Systems Recitation.
10/10/2015 E.R.Edwards 10/10/2015 Staffordshire University School of Computing Introduction to Android Overview of Android System Android Components Component.
Android Programming-Activity Lecture 4. Activity Inside java folder Public class MainActivity extends ActionBarActivity(Ctrl + Click will give you the.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Threads and Services. Background Processes One of the key differences between Android and iPhone is the ability to run things in the background on Android.
Understand applications and their components activity service broadcast receiver content provider intent AndroidManifest.xml.
Cosc 5/4730 Android Communications Intents, callbacks, and setters.
Android 13: Services and Content Providers Kirk Scott 1.
Services A Service is an application component that can perform long-running operations in the background and does not provide a user interface. An application.
로봇 모니터링 1/2 UNIT 20 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Message Queue Handler 2.
Mobile Programming Midterm Review
Services Background operating component without a visual interface Running in the background indefinitely Differently from Activity, Service in Android.
CSE 486/586, Spring 2014 CSE 486/586 Distributed Systems Android Programming Steve Ko Computer Sciences and Engineering University at Buffalo.
Technische Universität München Services, IPC and RPC Gökhan Yilmaz, Benedikt Brück.
Activities and Intents Chapter 3 1. Objectives Explore an activity’s lifecycle Learn about saving and restoring an activity Understand intents and how.
Speech Service & client(Activity) 오지영.
Services. What is a Service? A Service is not a separate process. A Service is not a thread. A Service itself is actually very simple, providing two main.
Developing Android Services. Objectives Creating a service that runs in background Performing long-running tasks in a separate thread Performing repeated.
Introduction to android
Concurrency in Android
Small talk with the UI thread
Reactive Android Development
Programming with Android:
Broadcast receivers.
CS371m - Mobile Computing Services and Broadcast Receivers
Lecture 7: Service Topics: Services, Playing Media.
Instructor: Mazhar Hussain
Lecture 7: Android Services
Cleveland State University
Notifications and Services
Activities and Intents
Android Mobile Application Development
The Android Activity Lifecycle
Android Application Development android.cs.uchicago.edu
Android Programming Lecture 9
Developing Android Services
Android Programming Lecture 8
CIS 470 Mobile App Development
Android Topics UI Thread and Limited processing resources
Activities and Intents
Activities and Intents
Android Developer Fundamentals V2
Threads, Handlers, and AsyncTasks
CIS 470 Mobile App Development
Lecture 7: Service Topics: Services, Broadcast Receiver, Playing Media.
SE4S701 Mobile Application Development
Mobile Programming Dr. Mohsin Ali Memon.
Activities and Fragments
Activities, Fragments, and Intents
CIS 470 Mobile App Development
Presentation transcript:

Service Services

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()

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

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.

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     } }

Service Lifecycle

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

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;

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();

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();

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.

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

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 service @Override 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; } } }

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(); } }

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; } }; ...

Using Messenger The client (activity) and the service exchanges Messages Message can contain simple data, object, and a Bundle

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();     }

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)

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;

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);

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)); }