Developing Android Services

Slides:



Advertisements
Similar presentations
Android Application Development Tutorial. Topics Lecture 6 Overview Programming Tutorial 3: Sending/Receiving SMS Messages.
Advertisements

Services. Application component No user interface Two main uses Performing background processing Supporting remote method execution.
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.
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.
Application Fundamentals. See: developer.android.com/guide/developing/building/index.html.
1 Working with the Android Services Nilanjan Banerjee Mobile Systems Programming University of Arkansas Fayetteville, AR
Chien-Chung Shen Manifest and Activity Chien-Chung Shen
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.
Software Architecture of Android Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
Android Services Mobile Application Development Selected Topics – CPIT Oct-15.
Cosc 5/4730 Broadcast Receiver. Broadcast receiver A broadcast receiver (short receiver) – is an Android component which allows you to register for system.
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.
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.
CS378 - Mobile Computing Intents. Allow us to use applications and components that are part of Android System – start activities – start services – deliver.
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.
Services 1 CS440. What is a Service?  Component that runs on background  Context.startService(), asks the system to schedule work for the service, to.
Mobile Programming Midterm Review
Services Background operating component without a visual interface Running in the background indefinitely Differently from Activity, Service in Android.
Lecture 2: Android Concepts
Technische Universität München Services, IPC and RPC Gökhan Yilmaz, Benedikt Brück.
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.
CS371m - Mobile Computing Intents 1. Allow us to use applications and components that are already part of Android System – start activities – start services.
Cosc 4735 Nougat API 24+ additions.
Lab7 – Appendix.
Android Application -Architecture.
Concurrency in Android
Permissions.
Lecture 2: Android Concepts
Broadcast receivers.
CS371m - Mobile Computing Services and Broadcast Receivers
Lecture 7: Service Topics: Services, Playing Media.
Instructor: Mazhar Hussain
Lecture 7: Android Services
Android Boot Camp for Developers Using Java, 3E
Notifications and Services
Activities and Intents
Android Mobile Application Development
Reactive Android Development
Android Application Development android.cs.uchicago.edu
Android Programming Lecture 9
CIS 470 Mobile App Development
Android Notifications (Part 2) Plus Alarms and BroadcastReceivers
CIS 470 Mobile App Development
Android Topics Asynchronous Callsbacks
Activities and Intents
CIS 470 Mobile App Development
Android Developer Fundamentals V2 Lesson 5
Service Services.
CIS 470 Mobile App Development
Lecture 7: Service Topics: Services, Broadcast Receiver, Playing Media.
Activities and Intents
Using threads for long running tasks.
SE4S701 Mobile Application Development
Lecture 2: Android Concepts
Mobile Programming Dr. Mohsin Ali Memon.
Activities, Fragments, and Intents
CIS 470 Mobile App Development
Mobile Programming Broadcast Receivers.
CA16R405 - Mobile Application Development (Theory)
Presentation transcript:

Developing Android Services Chapter 12

Objectives Creating a service that runs in the background Performing long-running tasks in a separate thread Performing repeated tasks in a service Having an activity and a service to communicate

Android Service Application component that runs (in background) without needing to interact with the user, e.g., playing background music, logging geographical coordinates, etc. => no need to present a UI to the user Three types Foreground: perform a task that is noticeable to the user (e.g., playing an audio track). Background: perform a task that isn’t directly noticed by the user (e.g., compacting storage) Bound: bound to an app component (e.g., activity); stop when no longer bound.

In-Class: Message Later App* App to send a message later using IntentService IntentService: simple way of creating a background service running in a new thread id=phoneEdit id=delayEdit id=msgEdit id=sendButton Steps Create a project named “Message Later”. Download layout from the course website. Create an IntentService named “MessageIntentService”. Code the intent service. Start the intent service from activity. *Dangerous permission required: android.permission.SEND_SMS

Message Later App (Cont.) Create a new IntentService named MessageIntentService. New > Service > Service (IntentService) (1) Uncheck the checkbox labeled “include helper start method?” (2) 1 2 Manifest: uncheck <application ... <service android:name=".MessageIntentService" android:exported="false" /> </application>

public class MessageIntentService extends IntentService { public MessageIntentService() { super("MessageIntentService"); } @Override protected void onHandleIntent(Intent intent) { String phone = intent.getStringExtra("phone"); String msg = intent.getStringExtra("message"); int delay = Integer.parseInt(intent.getStringExtra("delay")); try { Thread.sleep(delay * 1000); } catch (InterruptedException e) { SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phone, null, msg, null, null); MessageIntentService // starting a service Intent intent = new Intent(this, MessageIntentService.class); intent.putExtra("phone", …)); intent.putExtra("delay", …); intent.putExtra("message", …); startService(intent); MainActivity

Runtime Permission Request public class MainActivity extends AppCompatActivity { private static final int REQUEST_SMS_PERMISSION = 100; protected void onCreate(Bundle savedInstanceState) { ... requestSmsPermission(); } private void requestSmsPermission() { String smsPermission = Manifest.permission.SEND_SMS; int grant = ContextCompat.checkSelfPermission(this, smsPermission); if (grant != PackageManager.PERMISSION_GRANTED) { String[] permissions = new String[] { smsPermission }; ActivityCompat.requestPermissions(this, permissions, REQUEST_SMS_PERMISSION); @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_SMS_PERMISSION) { showToast(grantResults[0] == PackageManager.PERMISSION_GRANTED ? "Permission granted!" : "Permission not granted!"); private void showToast(String msg) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); }

Extra: Notification Service Improve the app to display a notification when the requested message has been sent. Use the built-in notification service of Android (see page 94 “Displaying Notifications” in Chapter 3).

Creating Service As a subclass of android.app.Service Override key framework methods including: int onStartCommand(Intent i, int flags, int startId) IBind onBind(Intent i) void onCreate() void onDestroy() Declare the service in AndroidManifest.xml*, e.g., <service android:name=".MyService"/> *Done automatically with Android Studio: New >> Service >> Service or Service (IntentService).

int onStartCommand(Intent intent, int flags, int startId) Called when the service is started by startService() startId: unique Id generated by system flags: additional info supplied by the system Return START_STICKY to make the service continue to run until explicitly stopped (<-> START_NOT_STICKY). call stopSelf() or stopService() to stop the service IBind onBind(Intent intent) Enable to bind an activity (by calling bindService()) to a service so as to access public elements such as fields and methods void onCreate() Called when the service is first created void onDestroy() Called when the service is stopped by calling stopService()

Starting/Stopping Service startService(new Intent(getBaseContext(), MyService.class)); startService(new Intent("edu.utep.cs.cs4330.MyService")); Need to make the service available to other applications <service android:name=".MyService"> <intent-filter> <action android:name="edu.utep.cs.cs4330.MyService"/> </intent-filter> </service> By default, service runs on the same thread that starts it (e.g., UI thread). stopService(new Intent(getBaseContext(), MyService.class));

Service Lifecycle

Long-Running Tasks In Service Perform in a new thread, but why? How? Thread class AsyncTask<Params, Progress, Result> class void onPreExecute() Invoked on the UI thread before doInBackground void doInBackground(Params...) Invoked on the background thread after onPreExecute void onProgressUpdate(Progress...) Invoked on UI thread after a call to publishProgress(Progress...) void onPostExecute(Result) Invoked on the UI thread after the background task finishes

Repeated Tasks In Service Performing repeated tasks in a service, e.g., alarm clock service that runs persistently in the background Use the java.util.Timer class providing several methods such as void scheduleAtFixedRate(TimerTask task, long delay, long period) new java.util.Timer().scheduleAtFixedRate( new java.util.TimerTask() { public void run() { /* ... */ } }, 0, // no delay 1000); // at every sec To cancel, call the Timer.cancel() method.

IntentService Subclass of Service to execute an asynchronous task on a new thread Automatically stop the service when completed (i.e., no need to call the stopSelf() method) Just need to override: protected void onHandleIntent(Intent i) that performs a task on a new thread Also need to add the service to manifest, e.g., <service android:name=".MyIntentService"/> IntentService onHandleIntent(Intent) Service onCreate() onStartCommand() onDestroy()

Service-Activity Communication Use the BroadCastReceiver In service: Intent broadcastIntent = new Intent(); broadcastIntent.setAction("MyAction"); getBaseContext().sendBroadcast(broadcastIntent); In activity: IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("MyAction"); registerReceiver(new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { ... } }, intentFilter);

Binding Activities To Services For an activity to access public members of a service Use the bindService() method in Activities Override the onBind() method in Services Refer to API document of the Service class

Side: Service vs. Thread Use Thread if: Work needs to be performed outside the main (UI) thread, but only while the user is interacting with the user. E.g., playing some music, but only while the activity is running. Thread will sleep if the device sleeps; Service can perform operations even if the device goes to sleep. Thread: music will play only if the app is active and screen display is on. Service: music will play even if the app is paused or screen display is off.

In-Class (Pair): Music Service Create a service that, given a music file URL, plays the music as a background service. MediaPlayer player = new MediaPlayer(); player.setDataSource(url); // “http://www.cs.utep.edu/cheon/cs4330/sample.mp3” player.prepare(); player.start(); When the playback is completed, the service should notify to the activity to display a toast message indicating the completion of the playback. setOnCompletionListener(MediaPlayer.OnCompletionListener)

Music Service URL 1: startService(i) <<activity>> MusicPlayer <<service>> MusicService 2. play the requested URL 3. broadcast an intent (done) Intent <<broadcast receiver>> … 4. Receive and toast (done)