Programming with Android: Notifications, Threads, Services

Slides:



Advertisements
Similar presentations
Module 1: BLOCK 1 / MAIN MENU
Advertisements

Android Application Development Tutorial. Topics Lecture 6 Overview Programming Tutorial 3: Sending/Receiving SMS Messages.
Programming with Android: SDK install and initial setup Luca Bedogni Marco Di Felice Dipartimento di Scienze dellInformazione Università di Bologna.
Programming with Android: Android for Tablets Luca Bedogni Marco Di Felice Dipartimento di Scienze dellInformazione Università di Bologna.
Programming with Android: Activities and Intents
Programming with Android: Activities
Programming with Android: Network Operations
RXQ Customer Enrollment Using a Registration Agent (RA) Process Flow Diagram (Move-In) Customer Supplier Customer authorizes Enrollment ( )
Document #07-2I RXQ Customer Enrollment Using a Registration Agent (RA) Process Flow Diagram (Move-In) (mod 7/25 & clean-up 8/20) Customer Supplier.
1 Hyades Command Routing Message flow and data translation.
7 Copyright © 2005, Oracle. All rights reserved. Creating Classes and Objects.
9 Copyright © 2005, Oracle. All rights reserved. Modularizing JavaServer Pages Development with Tags.
15 Copyright © 2005, Oracle. All rights reserved. Adding User Interface Components and Event Handling.
6 Copyright © 2005, Oracle. All rights reserved. Building Applications with Oracle JDeveloper 10g.
State of New Jersey Department of Health and Senior Services Patient Safety Reporting System Module 2 – New Event Entry.
1 Processes and Threads Creation and Termination States Usage Implementations.
Mike Scott University of Texas at Austin
Excel Functions. Part 1. Introduction 2 An Excel function is a formula or a procedure that is performed in the Visual Basic environment, outside the.
1 NatQuery 3/05 An End-User Perspective On Using NatQuery To Extract Data From ADABAS Presented by Treehouse Software, Inc.
Services. Application component No user interface Two main uses Performing background processing Supporting remote method execution.
Programming with Android: Android for Tablets Luca Bedogni Marco Di Felice Dipartimento di Scienze dell’Informazione Università di Bologna.
Programming with Android: System Architecture
1..
Executional Architecture
To the Assignments – Work in Progress Online Training Course
PSSA Preparation.
South Dakota Library Network MetaLib User Interface South Dakota Library Network 1200 University, Unit 9672 Spearfish, SD © South Dakota.
Chapter 16 Graphical User Interfaces John Keyser’s Modifications of Slides by Bjarne Stroustrup
User Friendly Item Relationship Maintenance A Family of Enhancements For iSeries 400 DMAS from  Copyright I/O International, 2006, 2007, 2008, 2010 Skip.
What’s new in WebSpace Changes and improvements with Xythos 7.2 Effective June 24,
TCP/IP Protocol Suite 1 Chapter 18 Upon completion you will be able to: Remote Login: Telnet Understand how TELNET works Understand the role of NVT in.
Chapter 9: Using Classes and Objects. Understanding Class Concepts Types of classes – Classes that are only application programs with a Main() method.
Programming with Android: Activities and Intents Luca Bedogni Marco Di Felice Dipartimento di Scienze dell’Informazione Università di Bologna.
Programming with Android: Activities and Intents Luca Bedogni Marco Di Felice Dipartimento di Informatica – Scienza e Ingegneria Università di Bologna.
Cosc 5/4730 Android Services. What is a service? From android developer web pages: Most confusion about the Service class actually revolves around what.
CSS216 MOBILE PROGRAMMING Android, Chapter 9 Book: “Professional Android™ 2 Application Development” by Reto Meier, 2010 by: Andrey Bogdanchikov (
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.
Cosc 4755 Android Notifications. There are a couple of ways to notify users with interrupting what they are doing The first is Toast, use the factory.
Programming with Android: Notifications, Threads, Services Luca Bedogni Marco Di Felice Dipartimento di Scienze dell’Informazione Università di Bologna.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Concurrency in Android with.
Using Intents to Broadcast Events Intents Can be used to broadcast messages anonymously Between components via the sendBroadcast method As a result Broadcast.
COMP 365 Android Development.  Perform operations in the background  Services do not have a user interface (UI)  Can run without appearing on screen.
This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit
DUE Hello World on the Android Platform.
16 Services and Broadcast Receivers CSNB544 Mobile Application Development Thanks to Utexas Austin.
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.
ANDROID L. Grewe Components  Java Standard Development Kit (JDK) (download) (latest version)  AndroidStudio.
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.
Notifications. A notification is a message you can display to the user outside of your application's normal UI. When you tell the system to issue a notification,
Themes and Menus: The Sudoku Example Content taken from book: “Hello, Android” by Ed Burnette Third Edition.
Mobile Programming Midterm Review
DKU-MUST Mobile ICT Education Center 10. Activity and Intent.
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.
Lecture 6: Process and Threads Topics: Process, Threads, Worker Thread, Async Task Date: Mar 1, 2016.
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.
Concurrency in Android
CS371m - Mobile Computing Services and Broadcast Receivers
Instructor: Mazhar Hussain
Activities and Intents
Android Mobile Application Development
Developing Android Services
Android Programming Lecture 8
Android Developer Fundamentals V2 Lesson 5
Service Services.
CIS 470 Mobile App Development
Presentation transcript:

Programming with Android: Notifications, Threads, Services Luca Bedogni Marco Di Felice Dipartimento di Scienze dell’Informazione Università di Bologna 1 1

Outline Notification Services: Status Bar Notifications Notification Services: Toast Notifications Thread Management in Android Thread: Handler and Looper Services: Local Services Services: Remote Services Broadcast Receivers 2

Android: Where are we now … TILL NOW  Android Application structured has a single Activity or as a group of Activities … Intents to call other activities Layout and Views to setup the GUI Events to manage the interactions with the user Activities executed only in foreground … What about background activities? What about multi-threading functionalities? What about external events handling? (c) Luca Bedogni 2012

Android: Where are we now … EXAMPLE: A simple application of Instantaneous Messaging (IM) Setup of the application GUI GUI event management Application Menu and Preferences Network functionalities (send/receive messages) Updates in background mode Notifications in case of message reception in background mode (c) Luca Bedogni 2012

Android: Service Notifications Types Service Notifications: Mechanism to notify information to the end-user on the occurrence of specific events .... Status Bar Notifications Toast Notifications (c) Luca Bedogni 2012

Android: Status Bar Notifications Used by background services to notify the occurrence of an event that requires a response … without interrupting the operations of the foreground activities! Display an icon on the Status Bar (top screen) Display a message in the Notification Window Fire an event in case the user selects the notification (c) Luca Bedogni 2012

Android: Status Bar Notifications Icon for the status bar Title and message PendingIntent to be fired when notification is selected Notification Manager OPTIONs: Android system component Responsible for notification management And status bar updates Ticket-text message Alert-sound Vibrate setting Flashing LED setting Customized layout (c) Luca Bedogni 2012

Android: Status Bar Notifications Follow these steps to send a Notification: Get a reference to the Notification Manager NotificationManager nm=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE) 2. Build the Notification message public Notification(int icon, CharSequence tickerText, long when) public void setLatestEvent(Context context, CharSequence contentTitle, CharSequence contentText, PendingIntent intent) 3. Send the notification to the Notification Manager public void notify(int id, Notification notification) (c) Luca Bedogni 2012

Android: Status Bar Notifications Build the notification object // Specificy icon, ticket message and time Notification notification = new Notification(R.drawable.icon, "This is a very basic Notification to catch your attention!", System.currentTimeMillis()); Define what will happen in case the user selects the notification // Build an explicit intent to NotificationActivity Intent intent = new Intent(this, NotificationActivity.class); PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); (c) Luca Bedogni 2012

Android: Status Bar Notifications Add (optional) flags for notification handling // Specificy that notification will disappear when handled notification.flags |= Notification.FLAG_AUTO_CANCEL; Send the notification to the Notification Manager // Set short and long message to be displayed on the notification window // Set the PendingIntent notification.setLatestEventInfo(this, "Notification", "Click to launch NotificationActivity", pIntent); notificationManager.notify(SIMPLE_NOTIFICATION_ID, notification); (c) Luca Bedogni 2012

Android: Status Bar Notifications Add a sound to the notification // Use a default sound notification.defaults |= Notification.DEFAULT_SOUND; Pass an URI to the sound field to set a different sound notification.sound = Uri.parse(file://sdcard/path/ringer.mp3); Use FLAG_INSISTENT to play the sound till notification is handled notification.flags |= Notification.FLAG_INSISTENT; (c) Luca Bedogni 2012

Android: Status Bar Notifications Add flashing lights to the notification // Use a default LED notification.defaults |= Notification.DEFAULT_LIGHTS; Define color and pattern of the flashing lights notification.ledARGB = 0xff00ff00; notification.ledOnMS = 300; notification. ledOffMS = 1000; notification.flags |= Notification.FLAG_SHOW_LIGHTS; (c) Luca Bedogni 2012

Android: Status Bar Notifications Add vibrations to the notification // Use a default vibration notification.defaults |= Notification.DEFAULT_VIBRATE; Define the vibration pattern // Set two vibrations, one starting at time 0 and with duration equal to 100ms long[] vibrate={0,100,200,300}; notification.vibrate = vibrate; (c) Luca Bedogni 2012

Android: Status Bar Notifications Some flags that can be used (see the documentation) FLAG_NO_CLEAR: Notification is not canceled FLAG_ONGOING_EVENT: Notify ongoing events (e.g. a call) FLAG_AUTO_CANCEL: Notification disappears as handled FLAG_INSISTENT: Reproduce sound till notification is handled FLAG_FOREGROUND_SERVICE: Notification from an active service … Also PendingIntents can have flags FLAG_CANCEL_CURRENT: PendingIntents are ovewritten FLAG_UPDATE_CURRENT: PendingIntents are updated (extra field) (c) Luca Bedogni 2012

Android: Toast Notifications A Toast Notification is a message that pops up on the surface of the window, and automatically fades out. Typically created by the foreground activity. Display a message text and then fades out Does not accept events! (use Status Bar Notifications instead) (c) Luca Bedogni 2012

Android: Toast Notifications A Toast Notification is a message that pops up on the surface of the window, and automatically fades out. Context context=getApplicationContext(); // Define text and duration of the notification CharSequence text=“This is a Toast Notification!”; int duration=Toast.LENGTH_SHORT; Toast toast=Toast.makeText(context, text, duration); // Send the notification to the screen toast.show(); (c) Luca Bedogni 2012

Android: Processes and Threads By default, all components of the same application run in the same process and thread (called “main thread” or “UI” thread). In Manifest.xml, it is possible to specify the process in which a component (e.g. an activity) should run through the attribute android:process. Processes might be killed by the system to reclaim memory. - Processes’ hierarchy to decide the importance of a process. - Five types: Foreground, Visible, Service, Background, Empty. (c) Luca Bedogni 2012

Android: Thread Management Android natively supports a multi-threading environment. An Android application can be composed of multiple concurrent threads. How to create a thread in Android? … Like in Java! extending the Thread class OR implementing the Runnable interface run() method executed when MyThread.start() is launched. (c) Luca Bedogni 2012

Android: Thread Management public class MyThread extends Thread { public MyThread() { super (“My Threads”); } public void run() { // do something myThread m=new MyThread(); m.start(); (c) Luca Bedogni 2012

Android: Thread Management The UI or main thread is in charge of dispatching events to the user interface widgets, and of drawing the elements of the UI. Do not block the UI thread. Do not access the Android UI components from outside the UI thread. QUESTIONS: How to update the UI components from worker threads? (c) Luca Bedogni 2012

Android: Thread Management Message-passing like mechanisms for Thread communication. MessageQueue  Each thread is associated a queue of messages Handler  Handler of the message associated to the thread Message  Parcelable Object that can be sent/received handleMessage(Message msg) sendMessage(Message msg) Message queue Handler THREAD1 THREAD2 (c) Luca Bedogni 2012

Android: Thread Management Message loop is implicitly defined for the UI thread … but it must be explicitly defined for worker threads. HOW? Use Looper objects … public void run() { Looper.prepare(); handler=new Handler() { public void handleMessage(Message msg) { // do something } Looper.loop(); (c) Luca Bedogni 2012

Android: Services A Service is an application that can perform long-running operations in background and does not provide a user interface. Activity  UI, can be disposed when it loses visibility Service  No UI, disposed when it terminates or when it is terminated by other components A Service provides a robust environment for background tasks … (c) Luca Bedogni 2012

Android: Services A Service is started when an application component starts it by calling startService(Intent). Once started, a Service runs in background indefinetely, even if the component that started it is destroyed. Termination of a Service: 1. selfStop()  self-termination of the service 2. stopService(Intent)  terminated by others 3. System-decided termination (i.e. memory shortage) (c) Luca Bedogni 2012

Android: Service Lifetime OnCreate() executed only once when the Service is created. OnCreate() startService() startService() OnStartCommand() startService() might cause the execution of OnCreate+OnStartCommand, or only of OnStartCommand, depending whether the Service is already running … RUNNING stopService() selfStop() onDestroy() (c) Luca Bedogni 2012

Android: Service Lifetime Two Types of Services: OnCreate() 1. Local Services: Start-stop lifecycle as the one shown. OnStartCommand() RUNNING 2. Remote/Bound Services: Bound to application components. Allow interactions with them, send requests, get results, IPC facilities. onDestroy() (c) Luca Bedogni 2012

Android: Foreground Services A Foreground Service is a service that is continuously active in the Status Bar, and thus it is not a good candidate to be killed in case of low memory. The Notification appears between ONGOING pendings. To create a Foreground Service: Create a Notification object Call startForeground(id, notification) from onStartCommand() Call stopForeground() to stop the Service. (c) Luca Bedogni 2012

Android: Bound Service A Bound Service allows components (e.g. Activity) to bind to the services, send requests, receive response. OnCreate() OnBind() onRebind() Client interacts with the Service … onUnbind() A Bound Service can serve components running on different processes (IPC). onDestroy() (c) Luca Bedogni 2012

Android: Bound Service Through the IBinder, the Component can send requests to the Service … bindService(Intent, ServiceConnection, flags) Component (e.g. Activity) Service When the connection is established, the Service will call the onServiceConnected and pass a reference of the IBinder to the Component. IBinder onBind() IBinder ServiceConnection onServiceConnected(ComponentName, IBinder) (c) Luca Bedogni 2012

Android: Bound Service When creating a Service, an IBinder must be created to provide an Interface that clients can use to interact with the Service … HOW? Extending the Binder class (local Services only) Extend the Binder class and return it from onBind() Only for a Service used by the same application Using the Android Interface Definition Language (AIDL) - Allow to access a Service from different applications. (c) Luca Bedogni 2012

Android: Bound Service public class LocalService extends Service { // Binder given to clients private final IBinder sBinder=(IBinder) new SimpleBinder(); @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return sBinder; } class SimpleBinder extends Binder { LocalService getService() { return LocalService.this; (c) Luca Bedogni 2012

Android: Bound Service public class MyActivity extends Activity { LocalService lService; private ServiceConnection mConnection=new ServiceConnection() { @Override public void onServiceConnected(ComponentName arg0, IBinder bind) { SimpleBinder sBinder=(SimpleBinder) bind; lService=sBinder.getService(); …. } public void onServiceDisconnected(ComponentName arg0) { }; (c) Luca Bedogni 2012

Android: Broadcast Receiver A Broadcast Receiver is a component that is activated only when specific events occur (i.e. SMS arrival, phone call, etc). Registration of the Broadcast Receiver to the event … Event  Intent Registration through XML code Registration through Java code Handling of the event. (c) Luca Bedogni 2012

Android: Broadcast Receiver A Broadcast Receiver is a component that is activated only when specific events occur (i.e. SMS arrival, phone call, etc). BROADCAST RECEIVER LIFETIME Single-state component … onReceive() is invoked when the registered event occurs After handling the event, the Broadcast Receiver is destroyed. EVENT OnReceive () (c) Luca Bedogni 2012

Android: Broadcast Receiver Registration of the Broadcast Receiver to the event … XML Code:  modify the AndroidManifest.xml <application> <receiver class=“SMSReceiver”> <intent-filter> <action android:value=“android.provider.Telephony.SMS_RECEIVED” /> </intent-filter> </receiver> </application> (c) Luca Bedogni 2012

Android: Broadcast Receiver Registration of the Broadcast Receiver to the event … In Java  registerReceiver(BroadcastReceiver, IntentFilter) receiver=new BroadcastReceiver() { … } protected void onResume() { registerReceiver(receiver, new IntentFilter(Intent.ACTION_TIME_TICK)); } protected void onPause() { unregisterReceiver(receiver); (c) Luca Bedogni 2012

Android: Broadcast Receiver How to send the Intents handled by Broadcast Receivers? void sendBroadcast(Intent intent) … No order of reception is specified void sendOrderedBroadcast(Intent intent, String permit) … reception order given by the android:priority field sendBroadcast() and startActivity() work on different contexts! (c) Luca Bedogni 2012