• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
MobAppDev (Fall 2013): Started Services, Intent Services, & Notifications
 

MobAppDev (Fall 2013): Started Services, Intent Services, & Notifications

on

  • 753 views

 

Statistics

Views

Total Views
753
Views on SlideShare
535
Embed Views
218

Actions

Likes
1
Downloads
0
Comments
0

39 Embeds 218

http://vkedco.blogspot.com 91
http://www.vkedco.blogspot.com 24
http://vkedco.blogspot.in 17
http://reader.aol.com 16
http://vkedco.blogspot.dk 7
http://www.blogger.com 4
http://vkedco.blogspot.sk 4
http://www.vkedco.blogspot.in 3
http://www.vkedco.blogspot.com.br 3
http://vkedco.blogspot.de 3
http://vkedco.blogspot.mx 3
http://www.vkedco.blogspot.kr 2
http://vkedco.blogspot.com.tr 2
http://vkedco.blogspot.cz 2
http://www.vkedco.blogspot.com.tr 2
http://vkedco.blogspot.com.au 2
http://vkedco.blogspot.kr 2
http://vkedco.blogspot.co.il 2
http://www.vkedco.blogspot.com.es 2
http://www.vkedco.blogspot.co.il 2
http://vkedco.blogspot.ae 2
http://vkedco.blogspot.com.es 2
http://vkedco.blogspot.co.uk 2
http://www.vkedco.blogspot.ro 2
http://vkedco.blogspot.it 2
http://www.vkedco.blogspot.ca 2
http://vkedco.blogspot.sg 1
http://vkedco.blogspot.ca 1
http://www.vkedco.blogspot.sg 1
http://www.linkedin.com 1
http://vkedco.blogspot.gr 1
http://vkedco.blogspot.nl 1
http://www.vkedco.blogspot.fr 1
http://www.vkedco.blogspot.co.uk 1
http://vkedco.blogspot.pt 1
http://www.vkedco.blogspot.nl 1
http://vkedco.blogspot.ie 1
http://www.vkedco.blogspot.it 1
http://www.vkedco.blogspot.de 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    MobAppDev (Fall 2013): Started Services, Intent Services, & Notifications MobAppDev (Fall 2013): Started Services, Intent Services, & Notifications Presentation Transcript

    • Android MobAppDev Started Services, Intent Services, & Notifcations Vladimir Kulyukin www.vkedco.blogspot.com
    • Outline Tasks & Services ● Started Services ● Started vs. Bound Services ● Notifications ● Intent Services ●
    • Tasks & Services
    • Three Thread Rules Android UI widgets are not thread-safe ● Main Thread (aka the UI thread) should not be blocked ● UI widgets cannot be accessed from outside the UI thread ●
    • Long Running Tasks ● ● ● ● What happens if you need to run a long-term job that is independent of any UI Enter services A Service is a way for an application to request Android to keep some task running for a while If there is not enough RAM, Android may still terminate services
    • What is a Service? ● ● ● A Service is an application component for performing long running operations in the background Services have no user interfaces, and are started by other application components Services may continue to run in the background even after the user switches to another application different from the application that started them
    • What Are Services For? ● Services have four primary areas of use:  Network transactions  Intensive I/O  Interaction with content providers  Multimedia operations (e.g., music, video)
    • Two Types of Services ● ● ● There are two board types of Android services: started (aka local) and bound (aka remote) Started services are typically used within one application Bound services are used for inter-process communication (IPC) that goes across application boundaries
    • Started Services ● ● ● ● A started service is started by an application component (typically, an activity) that calls startService() A started service usually performs a single operation that does not return results back to the caller directly The results are returned to the caller indirectly: a message on the status bar, saved file, updated content provider, etc After its work is done, a started service should stop itself
    • Bound Services ● ● ● A Service is bound when an application component binds to it by calling bindService() A Bound service offers a client-server interface that components can use to interact with the service, send requests, receive results, and do other IPC stuff Bound services offer the same type of functionality as remote method invocation (RMI) in Java
    • Bound Services ● ● ● Multiple components can bind to a bound service at once A Bound service is alive as long as at least one component is bound to it (the garbage collection inference counting principle) When a bound service has no bound components, it can be destroyed by Android
    • Services vs. Threads ● ● ● By default, services run on the main thread of their hosting processes & do not spawn their own threads unless explicitly told to do so What it means is that if you have a service doing a lot of CPU-intensive and/or blocking work (networking, playing music, I/O), the service may cause its hosting application to become non-responsive: this is the infamous Application Not Responding (ANR) Error A service may spawn their own threads
    • Services vs. Threads ● ● ● A service should be seriously considered only when you need to run some task in the background when the user is not interacting with the computation A thread is called for only when you need to do some task off the main thread only when the user is interacting with the application Example: when you need to TTS some text only when the user is looking at the screen, you should use a Thread (AsyncTask can also be used)
    • Access to Services ● ● ● Any application component can access a started or bound service A service can be declared private in AndroidManifest.xml If a service is private, any access from other applications is blocked
    • START_STICKY vs. START_NOT_STICKY ● ● ● These codes are used when the mobile device runs out of memory and kills the started service When a service is started with START_STICKY, Android re-creates it when it has enough memory after the service is terminated When a service is started with START_NOT_STICKY, Android does not bother to re-create it after it kills it
    • Started Services
    • Problem Write an application that uses a started service to compute all Catalan numbers less than or equal to 100,000 and displays them one by one in the status bar. source code is in StartedCatalanNumberService repo
    • Catalan Numbers ● ● ● ● Catalan numbers are a sequence of natural numbers The numbers get their name after Eugene Charles Catalan, a 19th century Belgian mathematician Catalan numbers figure prominently in combinatorics and recursive definitions Here are a few initial members of the Catalan sequence: 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, ...
    • Catalan Numbers: Two Interpretations ● One interpretation of Catalan numbers is the number of binary trees with n nodes: C(0) = 1, C(1) = 1, C(2) = 2, C(3) = 5 N=0 N=1 N=2 N=3 NULL ● Another interpretation is the number of expressions with n pairs of parentheses properly matched
    • Catalan Number Formula C0 = 1 C n +1 2( 2n + 1) = Cn n+2
    • Notifications ● ● ● Notifications notify the user of background events when no activity is present NotificationManager handles Notifications Notifications can be used to display messages & icons on the status bar, vibrate the phone, play audio alerts, broadcast intents, & flash lights
    • Notifications ● ● ● Notifications are helpful when multiple services are running the background doing different computations The user is unlikely to pay attention to any of them Displaying messages and icons on the status bar alerts the user to what is going on in the background
    • Getting NoficationManager & Notification.Builder // Two objects are needed to handle Notifications: NotificationManager // and Notification.Builder NotificationManager mNoteMngr = null; Notification.Builder mNoteBuilder = null; mNoteMngr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mNoteBuilder = new Notification.Builder(getApplicationContext()); Source code is in StartedCatalanNumberService.java
    • Constructing a Notification // Suppose that R.drawable.ornament_00 is a PNG image in /res/drawable; // mVibrationPattern is a pattern of vibrations (an array of long numbers); // msg is a string to display on the status bar // PendingIntent is an intent triggered by some event later mNoteBuilder.setSmallIcon(R.drawable.ornament_00) .setTicker(msg) .setWhen(System.currentTimeMillis()) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .setVibrate(mVibrationPattern); Notification note = mNoteBuilder.getNotification(); note.setLatestEventInfo(getApplicationContext(), SERVICE_CONTENT_TITLE, msg, mPendingIntent); Source code is in StartedCatalanNumberService.java
    • Screenshots
    • Solution ● ● ● Extend the Service class In the extended class (CatalanNumberService.java), define a NotificationManager member In the extended class, define a worker thread class ( CatalanServiceWorker) that implements the Runnable interface
    • Solution ● ● ● ● The worker thread and NotificationManager objects are created and in onCreate() The worker thread is also started in onCreate() Place ornament_00.png (the icon to be displayed in the status bar – you can replace it with your own image) in /res/drawable Declare the service in AndroidManifest.xml
    • Source Code Highlights
    • Starting a Service startService(new Intent(StartedCatalanServiceAct .this .getApplicationContext(), CatalanNumberService.class)); Source code is in StartedCatalanServiceAct.java
    • Stopping a Service stopService(new Intent(StartedCatalanServiceAct .this .getApplicationContext(), CatalanNumberService.class)); Source code is in StartedCatalanServiceAct.java
    • Spawning Threads from Services public void onCreate() { // Create and start a worker thread. mWorkerThread = new Thread( new CatalanServiceWorker(), SERVICE_NAME ); // Get off the main thread mWorkerThread.start(); } Source code is in StartedCatalanNumberService.java
    • Stopping Services stopService(new Intent(StartedCatalanServiceAct .this .getApplicationContext(), CatalanNumberService.class)); Source code is in StartedCatalanServiceAct.java
    • Declaring Services in AndroidManifest.xml <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:label="@string/app_name" android:name=".StartedCatalanServiceAct" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="CatalanNumberService" /> </application> Source code is in AndroidManifest.xml
    • Intent Services
    • Alternatives to Multi-Threading ● ● ● ● What if you do not want to live dangerously with threads? Suppose your application needs to handle one background request at a time Are there safer alternatives to creating and managing worker threads? The answer is – yes, it is IntentService
    • What is IntentService? ● ● ● ● IntentService is a subclass of Service IntentService handles all start requests one at a time IntentService is the best option if multithreading is not needed All one needs to do is to implement onHandleIntent() which receives the intent for each start request
    • What Does IntentService Do? ● ● ● ● Creates a worker thread that executes all intents given to onStartCommand() The worker thread is different from your application's main thread Creates a work queue that passes one intent at a time to onHandleIntent(): no multi-threading is guaranteed Stops the service after all start intents have been processed: no need to call stopSelf()
    • What Does IntentService Do? ● ● ● Provides a default implementation of onBind() that returns null Provides a default implementation of onStartCommand() that puts intents to the work queue and then to onHandleIntent() What do you need to do if you want to use IntentService:  Implement onHandleIntent()  Implement a constructor for the service
    • Problem Write an application that uses an IntentService to compute the sum of the first n members of the Catalan sequences and the Fibonacci sequence; the sequence is selected by the user. source code is in StartedSumIntentService repo
    • Screenshots 1 2 3 4
    • Source Code Highlights
    • Implementation of onHandleIntent() protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); String catSumKey = mRes.getString(R.string.cat_sum); String fibSumKey = mRes.getString(R.string.fib_sum); String nKey = mRes.getString(R.string.n_key); // 1. check if the bundle contains cat_sum or fib_sum key and n_key if ( (extras.containsKey(catSumKey) || extras.containsKey(fibSumKey)) && extras.containsKey(nKey) ) { long n = extras.getLong(nKey); // 2. if cat_sum key is present, then compute the catalan sum and post a notification message // on the status bar if ( extras.containsKey(catSumKey) ) { postNotificationMessage(compileCatNote(n, catalanSum(n))); } else { // 3. if fibo_sum key is present, then compute the fibonacci sum and post a notification message on // the status bar postNotificationMessage(compileFiboNote(n, fiboSum(n))); }} else { postNotificationMessage("Wrong arguments"); } mNoteMngr.cancel(R.string.app_id); } source code is in StartedSumIntentService.java
    • Starting an IntentService // 1. Create an Intent to run StartedSumIntentService.class Intent i1 = new Intent(getApplicationContext(), StartedSumIntentService.class); long n1 = Long.parseLong(mNEdtTxt.getText().toString().toString()); // 2. Put two key-value pairs (<cat_sum, true> and <n, n1>) into the Intent's bundle i1.putExtra(mRes.getString(R.string.cat_sum), true); i1.putExtra(mRes.getString(R.string.n_key), n1); // 3. start service with the created intent startService(i1); source code is in StartedSumIntentServiceAct.java