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

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

Embed Size (px)

Citation preview

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

1

Mobile Software Development Framework:

Android

2/28/2011

Y. Richard Yang

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

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

Recap: Android Framework Key Concepts

Activity: user activity and life cycle Example:ActivityLifeCycle

View: Visible screen for user

interaction

3

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

Recap: Intent as Component Glue

Intent: 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

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

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

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

Intent and Broadcast: Receiver

<receiver android:name=".CS434BroadcastReceiver" android:enabled="true">

<intent-filter>

<action android:name="edu.yale.cs434.RUN" />

</intent-filter>

</receiver>

6

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

Intent, Broadcast, Receiver, Notificationpublic 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

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

Recap: Do not Block

8

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

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

Recap: Do not Block

Numbers (Nexus One) ~5-25 ms – uncached flash reading a byte ~5-200+(!) ms – uncached flash writing tiny amount 100-200 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

9

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

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.

10

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

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.

11

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

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.

12

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

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

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

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

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

Examples

See BackgroundTimer

See HandleMessage

15

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

Tools

AsyncTask

IntentService

16

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

Tools: AsyncTask

17

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!

See GoogleSearch

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

Does Background Solve All Issues?

18

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

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?

19

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

Polling

Simple to implement Device periodically asks server for new

data Appropriate for content that changes

constantly Stock Quotes, News Headlines

20

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

Impact of Polling on Battery

Baseline: ~5-8 mA Network: ~180-200 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

21Source: Android development team at Google

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

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

22

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

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

23

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

C2DM Flow

Enabling cloud to device messaging 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 push24

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

C2DM

25

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

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

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

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.

} }

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

Receiving Registration ID

App receives the ID as an Intent com.google.android.c2dm.intent.REGISTRATIO

N 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

28

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

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

29

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

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);}

@Overrideprotected 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

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

Andriod

31

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

References

Online development guide http://developer.android.com/guide/index.htm

l

Book resources “The Android Developer’s Cookbook”

“Professional Android 2 Application Development”, by Reto Meier, from Yale Internet Resource

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

Android Debug Bridge (ADB)