1 Mobile Software Development Framework: Android 2/28/2011 Y. Richard Yang.

Slides:



Advertisements
Similar presentations
Android Application Development A Tutorial Driven Course.
Advertisements

Staying in Sync with Cloud 2 Device Messaging. About Me Chris Risner Twitter: chrisrisner.
1 Working with the Bluetooth radio Nilanjan Banerjee Mobile Systems Programming University of Arkansas Fayetteville, AR
The Activity Class 1.  One application component type  Provides a visual interface for a single screen  Typically supports one thing a user can do,
BroadcastReceiver.  Base class for components that receive and react to events  Events are represented as Intent objects  Intents received as parameter.
Cosc 4730 Brief return Sockets And HttpClient And AsyncTask.
Bluetooth. Bluetooth is an open, wireless protocol for exchanging data between devices over a short distance. –managed by the Bluetooth Special Interest.
Name Title Microsoft Corporation Push Notification Introduction and Platform Interaction.
1 Android: Event Handler Blocking, Android Inter-Thread, Process Communications 10/11/2012 Y. Richard Yang.
About me Yichuan Wang Android Basics Credit goes to Google and UMBC.
Developing Push Notifications (C2DM) for Android Vijai Co-Founder Adhish Technologies, Sweet’N’Spicy apps.
UI Design Patterns & Best Practices Mike Wolfson July 22, 2010.
Software Architecture of Android Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.
Mobile Computing Lecture#08 IntentFilters & BroadcastReceivers.
Debugging for Android 1 CS440. Debugging for Android  You have three options:  Android Debug Bridge (ADB)  Dalvik Debug Monitor Device (DDMS)  Device.
Google Cloud Messaging for Android (GCM) is a free service that helps developers send data from servers to their Android.
1 Mobile Software Development Framework: Android 2/23/2011 Y. Richard Yang.
Cosc 5/4730 Introduction: Threads, Android Activities, and MVC.
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
Integrating with Android Services. Introduction  Android has numerous built-in functionality that can be called from within your applications  SMS/MMS.
Cosc 5/4730 Broadcast Receiver. Broadcast receiver A broadcast receiver (short receiver) – is an Android component which allows you to register for system.
CS378 - Mobile Computing Intents.
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.
Mobile Programming Midterm Review
1 Mobile Software Development Framework: Android IPC; Mobile Push Notification 10/16/2012 Y. Richard Yang.
FCM Workflow using GCM.
1 Mobile Software Development Framework: Android Inter- Thread, Process Communications 10/11/2012 Y. Richard Yang.
1 © Donald F. Ferguson, All rights reserved.Modern Internet Service Oriented Application Development – Lecture 2: REST Details and Patterns Some.
Intents 1 CS440. Intents  Message passing mechanism  Most common uses:  starting an Activity (open an , contact, etc.)  starting an Activity.
Services Background operating component without a visual interface Running in the background indefinitely Differently from Activity, Service in Android.
1 Mobile Software Development Framework: IOS 10/2/2012 Y. Richard Yang.
Lecture 2: Android Concepts
Technische Universität München Services, IPC and RPC Gökhan Yilmaz, Benedikt Brück.
Speech Service & client(Activity) 오지영.
Intents and Broadcast Receivers Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution.
David Sutton SMS TELEPHONY IN ANDROID. OUTLINE  This week’s exercise, an SMS Pub Quiz  Simulating telephony on an emulator  Broadcast Intents and broadcast.
By: Eliav Menachi.  On Android, all application data (including files) are private to that application  Android provides a standard way for an application.
The Ingredients of Android Applications. A simple application in a process In a classical programming environment, the OS would load the program code.
CS371m - Mobile Computing Intents 1. Allow us to use applications and components that are already part of Android System – start activities – start services.
Multithreading Chapter 6. Objectives Understand the benefits of multithreading on Android Understand multi-threading fundamentals Know the Thread class.
Android Application -Architecture.
Concurrency in Android
Intents and Broadcast Receivers
Small talk with the UI thread
Lecture 2: Android Concepts
CS499 – Mobile Application Development
Broadcast receivers.
CS371m - Mobile Computing Services and Broadcast Receivers
CS434/534: Topics in Networked (Networking) Systems Mobile System: Android Component Composition/ Inter-process Communication (IPC) Yang (Richard) Yang.
Mobile Software Development Framework: Android Activity, View/ViewGroup, External Resources, Handler/ASyncTask 10/9/2012 Y. Richard Yang.
Notifications and Services
Reactive Android Development
Developing Android Services
Android Programming Lecture 8
Mobile Software Development Framework: Android
Application Development A Tutorial Driven Course
Android Network Layer; Location Management
Android Topics UI Thread and Limited processing resources
Android Topics Asynchronous Callsbacks
Activities and Intents
Android Topics Threads and the MessageQueue
Android Developer Fundamentals V2
Android Developer Fundamentals V2 Lesson 5
Threads, Handlers, and AsyncTasks
Lecture 2: Android Concepts
Mobile Programming Broadcast Receivers.
Presentation transcript:

1 Mobile Software Development Framework: Android 2/28/2011 Y. Richard Yang

2 Admin. r Schedule a time to meet with me on project ideas r Assignment 3: m two options: use the specified or design your own Android application (w/ minimal requirement)

Recap: Android Framework Key Concepts r Activity: user activity and life cycle  Example: ActivityLifeCycle r View: m Visible screen for user interaction 3

Recap: Intent as Component Glue r Intent: m an abstract description of an operation to be performed. r Intent filter m Register components as being capable of performing an action on a particular kind of data. r Implicit intent vs explicit intent r startActivity and startActivityForResult  Example: PassingDataBetweenActivities Comp.

Intent and Broadcast: Sender String action = "edu.yale.cs434.RUN"; Intent cs434BroadcastIntent = new Intent(action); cs434BroadcastIntent.putExtra("message", "Wake up."); sendBroadcast(cs434BroadcastIntent); 5 Example: IntentLaunch

Intent and Broadcast: Receiver 6

Intent, Broadcast, Receiver, Notification public class CS434BroadcastReceiver extends BroadcastReceiver { public static final String CUSTOM_INTENT = "edu.yale.cs434.RUN"; // Display an alert that we've received a public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(CUSTOM_INTENT)) { String message = (String)intent.getExtras().get("message"); CharSequence text = "Got intent " + CUSTOM_INTENT + " with " + message; int duration = Toast.LENGTH_SHORT; Toast mToast = Toast.makeText(context, text, duration); mToast.show(); } // end of if } // end of onReceive } 7

Recap: Do not Block 8 r ANRs (Application not responding) happen when m Main thread (“event”/UI) does not respond to input in 5 sec m A broadcast receiver does not finish in 10 sec r 5-10 sec is absolute upper bound

Recap: Do not Block r Numbers (Nexus One) m ~5-25 ms – uncached flash reading a byte m ~5-200+(!) ms – uncached flash writing tiny amount m ms – human perception of slow action m 108/350/500/800 ms – ping over 3G. varies! m ~1-6+ seconds – TCP setup + HTTP fetch of 6k over 3G r Rules m Notify users m Use background processing  Example: LaunchThread m Example: SimplyService 9

Background Processing using a Thread r Problem: m Background thread and UI thread are running concurrently and may have race conditions if they modify simultaneously r Solution: Android Handler m Use Handler to send and process Message and Runnable objects associated with a thread's MessageQueue.MessageMessageQueue 10

Android Handler r Each Handler instance is associated with a single thread and that thread's message queue. r A handler is bound to the thread / message queue of the thread that is creating it m from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue. 11

Using Handler r There are two main uses for a Handler: m to schedule messages and runnables to be executed as some point in the future; and m to enqueue an action to be performed on a different thread than your own. 12

Handler public class MyActivity extends Activity { [... ] // Need handler for callbacks to the UI thread final Handler mHandler = new Handler(); // Create runnable for posting final Runnable mUpdateResults = new Runnable() { public void run() { updateResultsInUi(); } protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); [... ] } 13

Handler protected void startLongRunningOperation() { // Fire off a thread to do some work that we shouldn't do directly in the UI thread Thread t = new Thread() { public void run() { mResults = doSomethingExpensive(); mHandler.post(mUpdateResults); } }; t.start(); } private void updateResultsInUi() { // Back in the UI thread -- update our UI elements based on the data in mResults [... ] } } 14

Examples r See BackgroundTimer r See HandleMessage 15

Tools r AsyncTask r IntentService 16

Tools: AsyncTask 17 private class DownloadFilesTask extends AsyncTask { protected Long doInBackground(URL... urls) { // on some background thread int count = urls.length; long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += Downloader.downloadFile(urls[i]); publishProgress((int) ((i / (float) count) * 100)); } return totalSize; } protected void onProgressUpdate(Integer... progress) { // on UI thread! setProgressPercent(progress[0]); } protected void onPostExecute(Long result) { // on UI thread! showDialog("Downloaded " + result + " bytes"); } new DownloadFilesTask().execute(url1, url2, url3); // call from UI thread! See GoogleSearch

Does Background Solve All Issues? 18

Example: Accessing Data in Cloud r A typical setting is that a device accesses data in the cloud, e.g., m background sync r Challenge: How do you keep data on a device fresh? 19

Polling r Simple to implement r Device periodically asks server for new data r Appropriate for content that changes constantly m Stock Quotes, News Headlines 20

Impact of Polling on Battery r Baseline: ~5-8 mA r Network: ~ mA m Tx more expensive than Rx r Assume radio stays on for 10 sec. m Energy per poll: ~0.50 mAh m 5 min frequency: ~144 mAh / day r Droid 2 total battery: 1400 mAh 21 Source: Android development team at Google

Solution: Push r Google Contacts, Calendar, Gmail, etc., use push sync r A single persistent connection from device to Google r Android Cloud to Device Messaging (C2DM) to make it a public service 22

C2DM Overview r Uses existing connection for Google services r Your servers send lightweight “data” messages to apps r Tell app new data available r Intent broadcast wakes up app r App supplies UI, e.g., Notification, if/as necessary 23

C2DM Flow r Enabling cloud to device messaging m App (on device) registers with Google, gets registration ID m App sends registration ID to its App Server r Per message m App Server sends (authenticated) message to Google m Google sends message to device r Disabling cloud to device messaging m App can unregister ID, e.g., when user no longer wants push 24

C2DM 25

Android Code: Registration to C2DM // Use the Intent API to get a registration ID // Registration ID is compartmentalized per app/device Intent regIntent = new Intent(“com.google.android.c2dm.intent.REGISTER”); // Identify your app regIntent.putExtra(“app”, PendingIntent.getBroadcast(this, 0, new Intent(), 0); // Identify role account server will use to send regIntent.putExtra(“sender”, OfSender); // Start the registration process startService(regIntent); 26

Receiving Registration ID 27 // Registration ID received via an Intent public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (“…REGISTRATION”.equals(action)) { handleRegistration(context, intent); } private void handleRegistration(Context context, Intent intent){ String id = intent.getExtra(“registration_id”); if ((intent.getExtra(“error”) != null) { // Registration failed. Try again later, with backoff. } else if (id != null) { // Send the registration ID to the app’s server. // Be sure to do this in a separate thread. }

Receiving Registration ID r App receives the ID as an Intent m com.google.android.c2dm.intent.REGISTRATION r App should send this ID to its server r Service may issue new registration ID at any time r App will receive REGISTRATION Intent broadcast r App must update server with new ID 28

Android: Content Provider r Each provider can expose its data as a simple table on a database model r Each content provider exposes a public URI that uniquely identifies its data set: m android.provider.Contacts.Phones.CONTENT_URI android.provider.Contacts.Photos.CONTENT_URI android.provider.CallLog.Calls.CONTENT_URI android.provider.Calendar.CONTENT_URI 29

Intent and Content Provider private void pickContact() { // Create an intent to "pick" a contact, as defined by the content provider URI Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI); startActivityForResult(intent, PICK_CONTACT_REQUEST); protected void onActivityResult(int requestCode, int resultCode, Intent data) { // If the request went well (OK) and the request was PICK_CONTACT_REQUEST if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) { // Perform a query to the contact's content provider for the contact's name Cursor cursor = getContentResolver().query(data.getData(), new String[] {Contacts.DISPLAY_NAME}, null, null, null); if (cursor.moveToFirst()) { // True if the cursor is not empty int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME); String name = cursor.getString(columnIndex); // Do something with the selected contact's name... } } } 30

Andriod 31

References r Online development guide m r Book resources m “The Android Developer’s Cookbook” m “Professional Android 2 Application Development”, by Reto Meier, from Yale Internet Resource

Android Debug Bridge (ADB)