Download presentation
Presentation is loading. Please wait.
1
Mobile Software Development Framework: Android
2/28/2011 Y. Richard Yang
2
Admin. Schedule a time to meet with me on project ideas Assignment 3:
two options: use the specified or design your own Android application (w/ minimal requirement)
3
Recap: Android Framework Key Concepts
Activity: user activity and life cycle Example: ActivityLifeCycle View: Visible screen for user interaction
4
Recap: Intent as Component Glue
an abstract description of an operation to be performed. Intent filter Register components as being capable of performing an action on a particular kind of data. Implicit intent vs explicit intent startActivity and startActivityForResult Example: PassingDataBetweenActivities
5
Intent and Broadcast: Sender
String action = "edu.yale.cs434.RUN"; Intent cs434BroadcastIntent = new Intent(action); cs434BroadcastIntent.putExtra("message", "Wake up."); sendBroadcast(cs434BroadcastIntent); Example: IntentLaunch
6
Intent and Broadcast: Receiver
<receiver android:name=".CS434BroadcastReceiver" android:enabled="true"> <intent-filter> <action android:name="edu.yale.cs434.RUN" /> </intent-filter> </receiver>
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 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 }
8
Recap: Do not Block ANRs (Application not responding) happen when
Main thread (“event”/UI) does not respond to input in 5 sec A broadcast receiver does not finish in 10 sec 5-10 sec is absolute upper bound
9
Recap: Do not Block Rules Numbers (Nexus One) Notify users
~5-25 ms – uncached flash reading a byte ~5-200+(!) ms – uncached flash writing tiny amount ms – human perception of slow action 108/350/500/800 ms – ping over 3G. varies! ~1-6+ seconds – TCP setup + HTTP fetch of 6k over 3G Rules Notify users Use background processing Example: LaunchThread Example: SimplyService
10
Background Processing using a Thread
Problem: Background thread and UI thread are running concurrently and may have race conditions if they modify simultaneously Solution: Android Handler Use Handler to send and process Message and Runnable objects associated with a thread's MessageQueue.
11
Android Handler Each Handler instance is associated with a single thread and that thread's message queue. A handler is bound to the thread / message queue of the thread that is creating it 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.
12
Using Handler There are two main uses for a Handler:
to schedule messages and runnables to be executed as some point in the future; and to enqueue an action to be performed on a different thread than your own.
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(); } }; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); [ ] }
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 [ ] } }
15
Examples See BackgroundTimer See HandleMessage
16
Tools AsyncTask IntentService
17
Tools: AsyncTask See GoogleSearch
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { 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!
18
Does Background Solve All Issues?
19
Example: Accessing Data in Cloud
A typical setting is that a device accesses data in the cloud, e.g., background sync Challenge: How do you keep data on a device fresh?
20
Polling Simple to implement
Device periodically asks server for new data Appropriate for content that changes constantly Stock Quotes, News Headlines
21
Impact of Polling on Battery
Baseline: ~5-8 mA Network: ~ mA Tx more expensive than Rx Assume radio stays on for 10 sec. Energy per poll: ~0.50 mAh 5 min frequency: ~144 mAh / day Droid 2 total battery: 1400 mAh Source: Android development team at Google
22
Solution: Push Google Contacts, Calendar, Gmail, etc., use push sync
A single persistent connection from device to Google Android Cloud to Device Messaging (C2DM) to make it a public service
23
C2DM Overview Uses existing connection for Google services
Your servers send lightweight “data” messages to apps Tell app new data available Intent broadcast wakes up app App supplies UI, e.g., Notification, if/as necessary
24
C2DM Flow Enabling cloud to device messaging Per message
App (on device) registers with Google, gets registration ID App sends registration ID to its App Server Per message App Server sends (authenticated) message to Google Google sends message to device Disabling cloud to device messaging App can unregister ID, e.g., when user no longer wants push
25
C2DM
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”, OfSender); // Start the registration process startService(regIntent);
27
Receiving Registration ID
// 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
App receives the ID as an Intent com.google.android.c2dm.intent.REGISTRATION App should send this ID to its server Service may issue new registration ID at any time App will receive REGISTRATION Intent broadcast App must update server with new ID
29
Android: Content Provider
Each provider can expose its data as a simple table on a database model Each content provider exposes a public URI that uniquely identifies its data set: android.provider.Contacts.Phones.CONTENT_URI android.provider.Contacts.Photos.CONTENT_URI android.provider.CallLog.Calls.CONTENT_URI android.provider.Calendar.CONTENT_URI
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... } } }
31
Andriod
32
References Online development guide Book resources
Book resources “The Android Developer’s Cookbook” “Professional Android 2 Application Development”, by Reto Meier, from Yale Internet Resource
33
Android Debug Bridge (ADB)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.