Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Mobile Software Development Framework: Android 2/28/2011 Y. Richard Yang."— Presentation transcript:

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

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

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

4 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.

5 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

6 Intent and Broadcast: Receiver 6

7 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 message. @Override 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

8 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

9 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 100-200 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

10 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

11 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

12 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

13 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(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); [... ] } 13

14 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

15 Examples r See BackgroundTimer r See HandleMessage 15

16 Tools r AsyncTask r IntentService 16

17 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

18 Does Background Solve All Issues? 18

19 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

20 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

21 Impact of Polling on Battery r Baseline: ~5-8 mA r Network: ~180-200 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

22 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

23 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

24 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

25 C2DM 25

26 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”, emailOfSender); // Start the registration process startService(regIntent); 26

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

28 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

29 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

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

31 Andriod 31

32 References r Online development guide m http://developer.android.com/guide/index.html http://developer.android.com/guide/index.html r Book resources m “The Android Developer’s Cookbook” m “Professional Android 2 Application Development”, by Reto Meier, from Yale Internet Resource

33 Android Debug Bridge (ADB)


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

Similar presentations


Ads by Google