Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Mobile Software Development Framework: IOS 10/2/2012 Y. Richard Yang 1 Admin. Homework 2 questions 2 Recap: TinyOS Hardware components motivated design Each component/module • specifies – the interfaces it provides – the interfaces/modules it uses • implements the functions in – the declared provided interfaces – event handlers in the declared used interfaces Configuration specifies the linkage among components/modules Event driven (triggered) handlers A single task queue 3 Recap: J2ME Java adaptation for mobile devices A major software concept is versioning Configurations Profiles For mobile phone devices, the key profile is MIDP 4 Recap: MIDP Key Concepts Lifecycle callbacks - startApp - pauseApp - destroyApp d=Display.getDisplay(this) d.setCurrent(disp) MIDP A set of commands Current Displayable Command listener 5 HelloWorldMIDlet.java import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class HelloWorldMIDlet extends MIDlet implements CommandListener { private Command exitCommand; private Display display; private TextBox t; public HelloWorldMIDlet() { display = Display.getDisplay(this); exitCommand = new Command("Exit", Command.EXIT, 2); t = new TextBox(“CS434", "Hello World!", 256, 0); t.addCommand(exitCommand); t.setCommandListener(this); } public void startApp() { display.setCurrent(t); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void commandAction(Command c, Displayable s) { if (c == exitCommand) { destroyApp(false); notifyDestroyed(); } } } 6 Extend MIDP GUI Key Concepts to General Setting App lifecycle callbacks/custom -start -pause -… View Group App View Group View Event listener/co ntroller Event listener/co ntroller View View Group View View View 7 System Support App lifecycle callbacks/custom -start -pause -… System schedules apps and notifies app on life cycle events View Group App View Group View Event listener/co ntroller Event listener/co ntroller View View Group View View View 8 System Support App lifecycle callbacks/custom -start -pause -… System schedules apps and notifies app on life cycle events View Group App View Group View Event listener/co ntroller Each view defines events it can handle, and system propagates events among view components Event listener/co ntroller View View Group View View View 9 GUI Design/Implementation Points App lifecycle callbacks/custom -start -pause -… View Group App -How to specify the customized callbacks? Event listener/co ntroller View Group View Event listener/co ntroller View View Group View View View 10 -How to specify the view structure for multiple display capabilities? GUI Design/Implementation Points App lifecycle callbacks/custom -start -pause -… View Group App -How to specify the customized callbacks? Event listener/co ntroller View Group View Event listener/co ntroller View View Group View View View 11 -How to specify the view structure for multiple display capabilities? GUI Design/Implementation Points App lifecycle callbacks/custom -start -pause -… View Group App -How to specify the customized callbacks? Event listener/co ntroller -How to link the callbacks defined in view to listener/controller? View Group View Event listener/co ntroller View View Group View View View 12 Outline Admin and recap Mobile/wireless development framework GNURadio TinyOS J2ME Android http://developer.android.com/index.html 13 Android A mobile OS, application framework, and a set of applications OS • Customized Linux kernel 2.6 and 3.x (Android 4.0 onwards) – E.g., default no X Windows, not full set of GNU libs Application development framework • Based on Java (J2SE not J2ME) • Dalvik Virtual Machine 14 Android Architecture 15 Seeing Android OS See http://developer.android.com/tools/workflo w/index.html Android SDK Manager (android) to start a simulator Android debug bridge (adb) can connect to an Android device and start a shell on the device Allows external XML resource files to specify views Mapping to Android App lifecycle callbacks/custom -start -pause -… View Group Activity -How to specify the customized callbacks: extend Activity class View Group View Event listener/co ntroller -How to link the callbacks defined in view to listener/controller: View.set…Listener() Event listener/co ntroller View View Group View View View 17 Application Framework (Android): Key Concepts Activity View/ViewGroup (Layout) External resources 18 Activity A single, focused thing that the user can do. Creating a window to place UI views Full-screen windows, floating windows, embedded inside of another activity Typically organized as a Stack Top Activity is visible Other activities are stopped Back button to traverse the Activity Stack Long Home shows the content of the Stack Activity: Example // MainActivity.java public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { // savedInstanceState holds any data that may have been saved // for the activity before it got killed by the system (e.g. // to save memory) the last time super.onCreate(savedInstanceState); setContentView(R.layout.main); // set a View } Activity: Manifest File To facility launching and managing Activities, each activity is announced in a manifest file Instead of a hardcode string in code, defines in resource Manifest the activity Android Project Resources 22 Android Activity Life cycle 23 Lifecycle Example See ActivityifeCycle 24 View A view component is a building block for user interface components. Two types of views TextView, EditText, Button, Form, TimePicker… ListView Composite (ViewGroup): LinearLayout, Leaf: Relativelayout, … http://developer.android.com/guide/tutorials/views/index.htm Programmatic Usage of Views // MainActivity.java public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { // savedInstanceState holds any data that may have been saved // for the activity before it got killed by the system (e.g. // to save memory) the last time super.onCreate(savedInstanceState); TextView tv new TextView(this); tv.setText("Hello!“); setContentView(tv); } Define View by XML Access View Defined by XML main.xml @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); } … TextView myTextView = (TextView)findViewById(R.id.myTextView); <?xml version=”1.0” encoding=”utf-8”?> <LinearLayout xmlns:android=”http://schemas.android.com /apk/res/android” android:orientation=”vertical” android:layout_width=”fill_parent” android:layout_height=”fill_parent”> <TextView android:id=”@+id/myTextView” android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:text=”Hello World, HelloWorld” /> </LinearLayout> External Resources Compiled to numbers and included in R.java file 29 Linking Views and Handlers/Controllers onKeyDown. onKeyUp onTrackBallEvent onTouchEvent registerButton.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) {….}} myEditText.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { … return true; } return false; }}); } Example: TipCalc 31 Event handler and ANR ANRs (Application not responding) happen when Main thread (“event”/UI) does not respond to input in 5 sec 5-10 sec is absolute upper bound 32 ANR 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 33 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. 34 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. 35 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. 36 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); [...] } 37 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 [...] } } 38 Examples See BackgroundTimer See HandleMessage 39 Tools AsyncTask IntentService 40 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! 41 Does Background Solve All Issues? 42 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? 43 Polling Simple to implement Device periodically asks server for new data Appropriate for content that changes constantly Stock Quotes, News Headlines 44 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 Source: Android development team at Google 45 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 46 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 47 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 push 48 C2DM 49 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); 50 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. } } 51 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 52 Application Framework (Android): Key Concepts Activity and view Visible screen for user interaction External resources 53 External Resources 54 Application Framework (Android): Key Concepts Activity and view Visible screen for user interaction External resources Service 55 Application Framework (Android): Key Concepts Activity View/ViewGroup (Layout) External resources Service Intercommunications Communication among apps: - Intent - broadcast - data provider App App 56 Service: Working in Background A basic function of Android Service: 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). The system to schedule work for the service, to be run until the service or someone else explicitly stop it. NO GUI, higher priority than inactive Activities Note 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. 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). Application and Component Glues Intent An intent is an abstract description of an operation to be performed. To invoke operations from your own or others Can pass data back and forth between app. Intent Filter Register Activities, Services, and Broadcast Receivers as being capable of performing an action on a particular kind of data. Intent Description <Component name> Action Data Category, e.g., LAUNCHER 59 Intent Usage Pass to Context.startActivity() or Activity.startActivityForResult() to launch an activity or get an existing activity to do something new. Pass to Context.startService() to initiate a service or deliver new instructions to an ongoing service. Pass to Context.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. Pass to any of the broadcast methods (such as Context.sendBroadcast(), Context.sendOrderedBroadcast(), or Context.sendStickyBroadcast()) are delivered to all interested broadcast receivers. Many kinds of broadcasts originate in system code. 60 Android: Broadcast Receiver Sending a broadcast: Context.sendBroadcast(Intent intent, String receiverPermission) Context.sendOrderedBroadcast() Receiving broadcast: Intent registerReceiver (BroadcastReceiver receiver, IntentFilter filter) 61 Intent Resolution: Explicit Explicit intents: component identified Intent myIntent = new Intent(IntentController.this, TipCal.class); startActivity(myIntent); 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="Intent1"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".TipCal"></activity> </application> 62 Intent Resolution: Implicit Implicit intents System matches an intent object to the intent filters of others http://developer.android.com/guide/topics/intents/intents-filters.html 63 Intent filter action category data 64 Intent Example II: Implicit String action = "android.intent.action.VIEW"; Uri data = Uri.parse("http://www.google.com"); Intent myIntent = new Intent(action, data); startActivity(myIntent); AndroidManifest.xml file for com.android.browser <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <scheme android:name="http" /> <scheme android:name="https" /> <scheme android:name="file" /> </intent-filter> 65 Intent Example II: Implicit String action = "android.intent.action.DIAL"; String phno = "tel:4326400"; Uri data = Uri.parse(phno); Intent dialIntent = new Intent(action, data); startActivity(dialIntent); A Design Template: Invoker 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); 67 A Design Template: Provider <activity android:name=".Booking" android:label=“Booking"> <intent-filter> <action android:name=“com.hotelapp.ACTION_BOOK" /> <data android:scheme=“hotel" android:host=“name”/> </intent-filter> </activity> For more complex data passing, please read the tutorial 68 A Design Template: Provider @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(); } 69 Intent and Broadcast: Sender String action = "edu.yale.cs434.RUN"; Intent cs434BroadcastIntent = new Intent(action); cs434BroadcastIntent.putExtra("message", "Wake up."); sendBroadcast(cs434BroadcastIntent); Example: IntentLaunch 70 Intent and Broadcast: Receiver <receiver android:name=".CS434BroadcastReceiver" android:enabled="true"> <intent-filter> <action android:name="edu.yale.cs434.RUN" /> </intent-filter> </receiver> 71 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 } 72 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 73 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... } } } 74 Windows .NET Compact Framework Similar to J2ME Scales down a popular programming environment to ease learning the .NET CF is a subset of the full .NET framework with some additions designed for resource constrained devices 1,400 classes for .NET CF vs. 8,000 for full 27 UI controls for .NET CF vs. 52 for full 1.5 MB for .NET CF vs. 30 MB for full Uses versioning to avoid using lowest common denominator pocket PC pocket PC phone version smart phone version Uses virtual machines to mask device heterogeneity programming languages compile to MSIL • MSIL is JIT compiled on the device • MSIL code is smaller than native executables • MSIL allows your code to be processor independent 75 Android Linux kernel as foundation Java based framework (J2SE not J2ME) Dalvik Virtual machine Nice features Touch screen, accelerometer, compass, microphone, camera, GPS, GSM, EDGE, and 3G networks, WiFi, Bluetooth, Near field communications Media, SQLite, WebKit, SSL Location-based service, map (Google API) 76