Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Mobile Software Development Framework: Android Inter- Thread, Process Communications 10/11/2012 Y. Richard Yang.

Similar presentations


Presentation on theme: "1 Mobile Software Development Framework: Android Inter- Thread, Process Communications 10/11/2012 Y. Richard Yang."— Presentation transcript:

1 1 Mobile Software Development Framework: Android Inter- Thread, Process Communications 10/11/2012 Y. Richard Yang

2 2 Outline r Admin r Android m Basic concepts Activity, View, External Resources, Listener m Inter-thread communications Handler, ASyncTask m Inter-process communications Intent, Broadcast, BroadcastReceiver, Service

3 3 Admin. r HW2 m Due: Friday @ 11:55 pm

4 Recap: Mobile GUI App Workflow App App lifecycle callbacks/custom -start -pause -… Display Composite Displa y Composite Displa y Display Composite Displa y Data/ Model Event Handle r Display Composite Display Composite Display

5 5 Recap: Android UI App Basic Concepts r Activity r View/ViewGroup m External definition of views in XML m findViewById() to reduce coupling r Link view events to event handlers m set…Listener()

6 Example: TipCalc Set listener: 6 public class TipCalcActivity extends Activity implements OnClickListener { … @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tip_calc); Button calc = (Button)findViewById(R.id.calculate); calc.setOnClickListener(this); } … }

7 Example: TipCalc Event Handler Handler: 7 @Override public void onClick(View arg0) { EditText amountText = (EditText)findViewById(R.id.amount_value); // get input from UI double amt=Double.parseDouble(amountText.getText().toString()); // compute output double tipD = amount * 0.15; // update UI String tipT = String.format("%.2f", tipD); TextView tipText = (TextView)findViewById(R.id.tip_value); tipText.setText(tipT); }

8 Event Handler Execution 8 r Event handler executed by the main/UI thread UI events system events message Looper UI (main) thread http://www.java2s.com/Open-Source/Android/android- core/platform-frameworks-base/android/os/Looper.java.htm

9 Event Handler and Responsiveness 9 r Event handler blocks events in the msg queue from being processed => slow running handler leads to no UI response http://developer.android.com/guide/practices/responsiveness.html UI events system events message Looper UI (main) thread

10 Responsiveness: Numbers (Nexus One) r ~5-25 ms – uncached flash reading a byte r ~5-200+(!) ms – uncached flash writing tiny amount r 100-200 ms – human perception of slow action r 108/350/500/800 ms – ping over 3G. varies! r ~1-6+ seconds – TCP setup + HTTP fetch of 6k over 3G 10

11 Event Handler and ANR 11 r Android system detects no response m Main thread (“event”/UI) does not respond to input in 5 sec

12 12 Example r play_music

13 13 Discussion r What are some design options if an event may take a while to be processed m Time consuming loading process, e.g., slow onCreate m Heavy computation, e.g., voice recognition, update map display m Networking access m …

14 14 Typical Design Guidelines r Notify user m E.g., progress bar, progress dialog m A splash screen r If possible, non-blocking, incremental update UI m E.g., gradual add items to map r Whenever possible, release UI thread ASAP m Keep event handler simple m Post heavy processing off the UI thread

15 Example: Background Thread r Use a background thread to do the task r Background thread behavior controlled by state r State controlled by event handler r See PlayMusic 15

16 Service: Working in Background r A basic function of Android Service: m A facility for an application to tell the system about something it wants to be doing in the background (even when the user is not directly interacting with the application). m The system to schedule work for the service, to be run until the service or someone else explicitly stop it. m NO GUI, higher priority than inactive Activities r Note m A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of. m A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).

17 Background Thread vs UI Thread r Problem: m Background thread and UI thread are running concurrently and may have race conditions if they modify UI simultaneously (e.g., UI switches to a different orientation) m A major sin of programming: concurrency bugs r Example: LoadingScreen 17

18 Example: LoadingScreen 18 public class LoadingScreen extends Activity implements Runnable { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.loading); // start a new thread to load Thread thread = new Thread(this); thread.start(); } public void run(){ longRunningTask(); setContentView(R.layout.main); } … }

19 Solution r Background thread does not directly modify UI: send msg to UI thread, who processes the msg 19

20 Android Handler r Android’s mechanism to send and process Message and Runnable objects associated with a thread's MessageQueue.MessageMessageQueue r Each Handler instance is associated with a single thread and that thread's message queue m A handler is bound to the thread / message queue of the thread that creates it m from that point on, it will deliver messages and runnables to that message queue m That thread processes msgs 20

21 Android Handler 21

22 Using Handler: Examples r There are two main uses for a Handler m to schedule messages and runnables to be executed as some point in the future postDelayed(Runnable, delayMillis) m to enqueue an action to be performed on a different thread than your own. post(Runnable) 22

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

24 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(mUpdateResultsTask); } }; t.start(); } private void updateResultsInUi() { // Back in the UI thread -- update our UI elements based on the data in mResults [... ] } } 24

25 Example: Fixing LoadingScreen 25 public class LoadingScreen extends Activity implements Runnable { private Handler mHandler = new Handler(); // UI handler @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.loading); // start a new thread to load Thread thread = new Thread(this); thread.start(); } public void run(){ longTask(); mHandler.post(mSetFinalViewTask); } private Runnable mSetFinalViewTask = new Runnable() { public void run() { setContentView(R.layout.main); } }; }

26 Example: BackgroundTimer 26

27 Common Pattern 27 private Handler mHandler = new Handler(); // UI handler private Runnable longTask = new Runnable() { // processing thread public void run() { while (notFinished) { // doSomething mHandler.post(taskToUpdateProgress); } // mHandler.post(taskToUpdateFinalResult) }; Thread thread = new Thread(longTask); thread.start();

28 AsyncTask as Abstraction 28 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

29 29

30 30 Outline r Admin r Android m Basic concepts Activity, View, External Resources, Listener m Inter-thread communications Handler, ASyncTask m Inter-process communications Intent, Broadcast, BroadcastReceiver, Service

31 31 Inter-Process Communications (IPC) r Inter-thread communications are for one activity r Inter-process communication is designed to promote the development of complex applications, by allowing developers to reuse existing data and services from other applications. r One may also use IPC for intra-app communications (e.g., between Activities of the same app)

32 Discussion: IPC Use Cases r One component of Android sends messages to another component of Android r An IPC message in Android is called Intent 32 Component

33 Target: Activity  startActivity() or startActivityForResult() to launch an activity or get an existing activity to do something new. 33 Component Activity

34 Target: Service  startService() to initiate a service or deliver new instructions to an ongoing service.  bindService() to establish a connection between the calling component and a target service. It can optionally initiate the service if it's not already running. 34 Component Service

35 Target: BroadcastReceiver  broadcastIntent() to send messages to all interested broadcast receivers. m Many kinds of broadcasts originate in system code, e.g., boot, battery low 35 Component Broadcast Receiver

36 Target: Data Provider  startActivityForResult() may target to a data provider (e.g., Contacts) 36 Component Data Provider

37 Example: A SocialApp 37

38 Android Application Component: Gang of Four 38

39 39 Outline r Admin r Android m Basic concepts Activity, View, External Resources, Listener m Inter-thread communications Handler, ASyncTask m Inter-process communications Intent

40 Application and Component Glues: Intent r Intent m An intent is an abstract description of an operation to be performed. Indicate operations from your own or others http://developer.android.com/reference/android/content/Intent.html Component

41 Intent Data Structure r Primary pieces of info in an Intent m Action: The general action to be performed ACTION_VIEW, ACTION_DIAL, ACTION_EDIT, … Your own definition of strings m Data: a URI tel:123 content://contacts/people/1 http://zoo.cs.yale.edu/classes/cs434 hotel://name/Omni_New_Haven r Other attributes m Category m Type (MIME type) m Component (class name) m Extras (key-value store) 41 scheme host path

42 Intent Resolution: Explicit Intent r Explicit Intent: specifies the exact class to run 42 public class IntentController extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.intentcontroller); // launch tip cal button Button tipBtn = (Button) findViewById(R.id.tipButton); tipBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent tipIntent = new Intent(IntentController.this, TipCal.class); startActivity(tipIntent); } }); class name Context

43 Explicit Intent and Manifest 43 r Make sure AndroidManifest.xml announces activities to be started <application android:icon="@drawable/icon” android:label="@string/app_name" > <activity android:name=".IntentController” android:label="IntentController" > <activity android:name=".TipCal android:label="TipCal" > Shown in Launcher Announce class See IntentController

44 Explicit Intent 44 Yelp Map App Name: MapActivity To: MapActivity Only the specified destination receives this message

45 Intent Resolution: Implicit Intent r Intent does not specify exact class to run m Info in the Intent used by the system to determine the best component, at run time, to handle the intent r Matching based on Intent Filter m Register Activities, Services, and Broadcast Receivers register Intent Filter to indicate as being capable of performing an action on a particular kind of data r Q: benefit of dynamic binding? 45 http://developer.android.com/guide/topics/intents/intents-filters.html

46 Implicit Intents 46 Yelp Clock App Map App Handles Action: VIEW Handles Action: DISPLAYTIME Implicit Intent Action: VIEW

47 Implicit Intents 47 Yelp Browser App Map App Handles Action: VIEW Implicit Intent Action: VIEW

48 Intent Filter 48 action category data

49 Intent Resolution: Implicit Intent 49 public class IntentController extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.intentcontroller); // launch dial button Button dialBtn = (Button) findViewById(R.id.dialButton); dialBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String action = "android.intent.action.DIAL"; String phno = "tel:4326400"; Uri data = Uri.parse(phno); Intent dialIntent = new Intent(action, data); startActivity(tipIntent); } }); data action See IntentController

50 Implicit Intent and Manifest r AndroidManifest.xml file for com.android.browser 50 String action = "android.intent.action.VIEW"; Uri data = Uri.parse("http://www.google.com"); Intent myIntent = new Intent(action, data); startActivity(myIntent);

51 A Design Template: Invoker 51 String action = “com.hotelapp.ACTION_BOOK"; String hotel = “hotel://name/“ + selectedHotel; Uri data = Uri.parse(hotel); Intent bookingIntent = new Intent(action, data); startActivityForResults(bookingIntent, requestCode);

52 A Design Template: Provider 52

53 A Design Template: Provider 53 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Intent intent = getIntent(); // why am I called String action = intent.getAction(); Uri data = intent.getdata(); String hotelName = data.getPath(); // do the booking setResult(RESULT_OK); finish(); }

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

55 Intent and Broadcast: Receiver 55

56 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 } 56

57 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 57

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


Download ppt "1 Mobile Software Development Framework: Android Inter- Thread, Process Communications 10/11/2012 Y. Richard Yang."

Similar presentations


Ads by Google