Download presentation
Presentation is loading. Please wait.
Published byEmily Carpenter Modified over 6 years ago
1
Mobile Software Development Framework: Android Activity, View/ViewGroup, External Resources, Handler/ASyncTask 10/9/2012 Y. Richard Yang
2
Admin. Homework 2 questions
3
Recap: TinyOS Hardware components motivated design Execution model
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 Execution model Event driven (triggered) handlers, who may post tasks to a FIFO task queue
4
Recap: J2ME Java adaptation for mobile devices
A major software concept is versioning Configurations Profiles For mobile phone devices, the key profile is MIDP
5
Recap: MIDP Key Concepts
Lifecycle callbacks startApp pauseApp destroyApp disp.addCommand() d=Display.getDisplay(this) d.setCurrent(disp) A set of commands MIDP Current Displayable Command listener disp.setCommandListener()
6
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();
7
Recap: J2ME Key software concept
Screen real-estate is limited => Focus on one thing at a time
8
Recap: J2ME Key software concept
Screen real-estate is limited => Focus on one thing at a time
9
Mobile GUI Workflow App lifecycle callbacks/custom start pause … App
10
Mobile GUI Workflow: Do One Thing
App lifecycle callbacks/custom start pause … App Display Composite Display Composite
11
Mobile GUI Workflow: Display Content Based on Underlining Data
App lifecycle callbacks/custom start pause … App Display Composite Display Composite Data/Model Data/Model
12
Mobile GUI Workflow: Handle Events
App lifecycle callbacks/custom start pause … App Display Composite Display Composite Event Handler Event Handler Data/Model Data/Model
13
Mobile GUI Workflow: Switch to Another GUI
App lifecycle callbacks/custom start pause … App Display Composite Display Composite Display Composite Display Composite Event Handler Event Handler Data/Model Data/Model
14
Discussion Key design points for mobile GUI app
App life cycle scheduling and customization Support to construct display Event scheduling How to link event, display, handler, data
15
Typical Design: App App
Framework reacts to app events and invokes app lifecycle event handlers Typical Design: App App lifecycle callbacks/custom start pause … App Display Composite Display Composite Event Handler Event Handler Data/Model Data/Model
16
How to Provide App LifeCycle Handlers?
App class implements it Inheritance App class does not implement it Delegate Command listener
17
System captures UI events; and puts them in a msg queue of the app
System captures UI events; and puts them in a msg queue of the app. A UI thread processes the queue Typical Design: UI App lifecycle callbacks/custom start pause … App Display Composite Display Composite Event Handler Event Handler Data/Model Data/Model
18
Example: IOS 10/4/12
19
How to Provide Display Component Event Handlers?
Display Component class implements it Inheritance Typically a bad idea Display Component class does not implement it Makes Display reusable Delegate Command listener
20
Event Handler/Controller Design Issues
To increase reusability, it is ideal to separate layout from presentation
21
Outline http://developer.android.com/index.html Admin and recap
Mobile/wireless development framework GNURadio TinyOS J2ME IOS Android
22
Android A mobile OS, application framework, and a set of applications
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
23
Android Architecture
24
Seeing Android OS See 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
25
Mapping to Android Allows external XML resource files to specify views App lifecycle callbacks/custom start pause … App Display Composite Display Composite -How to specify the customized callbacks: extend Activity class -How to link the callbacks defined in view to listener/controller: View.set…Listener() Event Handler Event Handler Data/Model Data/Model
26
Application Framework (Android): Key Concepts
Activity View/ViewGroup (Layout) External resources
27
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
28
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 res/strings Manifest the activity
29
Android Project Resources
30
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(… ); // set a View }
31
View A view component is a building block for user interface components. Two types of views Leaf: TextView, EditText, Button, Form, TimePicker… ListView Composite (ViewGroup): LinearLayout, Relativelayout, …
32
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); }
33
Define View by XML
34
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=” android:orientation=”vertical” android:layout_width=”fill_parent” android:layout_height=”fill_parent”> <TextView android:layout_height=”wrap_content” android:text=”Hello World, HelloWorld” /> </LinearLayout>
35
External Resources Compiled to numbers and included in R.java file
36
Hello Example See HelloStart
37
Android Activity Life Cycle
38
Android Activity Life Cycle
39
Lifecycle Example See ActivityifeCycle
40
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; }});
41
Example: TipCalc
42
Event Handler and ANR Event handler executed by the main/UI thread
ANRs (Application not responding) happen when Main thread (“event”/UI) does not respond to input in 5 sec UI events system events
43
Event Handler and ANR
44
ANR Rules Numbers (Nexus One) Notify users Use background processing
~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
45
Example Background Processing
LaunchInThread
46
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.
47
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.
48
Android Handler
49
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.
50
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(); } }; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); [ ] }
51
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 [ ] } }
52
Examples See BackgroundTimer See LoadingScreen
53
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!
55
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).
56
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.
57
Intent Description <Component name> Action Data
Category, e.g., LAUNCHER
58
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.
59
Android: Broadcast Receiver
Sending a broadcast: Context.sendBroadcast(Intent intent, String receiverPermission) Context.sendOrderedBroadcast() Receiving broadcast: Intent registerReceiver (BroadcastReceiver receiver, IntentFilter filter)
60
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 <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>
61
Intent Resolution: Implicit
Implicit intents System matches an intent object to the intent filters of others
62
Intent filter action category data
63
Intent Example II: Implicit
String action = "android.intent.action.VIEW"; Uri data = Uri.parse(" 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>
64
Intent Example II: Implicit
String action = "android.intent.action.DIAL"; String phno = "tel: "; Uri data = Uri.parse(phno); Intent dialIntent = new Intent(action, data); startActivity(dialIntent);
65
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);
66
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
67
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(); }
68
Intent and Broadcast: Sender
String action = "edu.yale.cs434.RUN"; Intent cs434BroadcastIntent = new Intent(action); cs434BroadcastIntent.putExtra("message", "Wake up."); sendBroadcast(cs434BroadcastIntent); Example: IntentLaunch
69
Intent and Broadcast: Receiver
<receiver android:name=".CS434BroadcastReceiver" android:enabled="true"> <intent-filter> <action android:name="edu.yale.cs434.RUN" /> </intent-filter> </receiver>
70
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 }
71
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
72
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... } } }
73
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
74
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)
75
Does Background Solve All Issues?
76
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?
77
Polling Simple to implement
Device periodically asks server for new data Appropriate for content that changes constantly Stock Quotes, News Headlines
78
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
79
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
80
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
81
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
82
C2DM
83
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);
84
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.
85
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
86
Application Framework (Android): Key Concepts
Activity and view Visible screen for user interaction External resources
87
External Resources
88
Application Framework (Android): Key Concepts
Activity and view Visible screen for user interaction External resources Service
89
Application Framework (Android): Key Concepts
Activity View/ViewGroup (Layout) External resources Service Intercommunications App Communication among apps: Intent broadcast data provider
90
Mobile GUI Workflow: Switch to Another
App lifecycle callbacks/custom start pause … App Display Composite Display Composite Display Composite Display Composite Data/Model Data/Model
91
Extend MIDP GUI Key Concepts to General Setting
Display Composite Display Composite
92
Extend MIDP GUI Key Concepts to General Setting
App lifecycle callbacks/custom start pause … App View Group Event listener/controller View View Group View Event listener/controller View View Group View View
93
System schedules apps and notifies app on life cycle events
System Support App lifecycle callbacks/custom start pause … App View Group Event listener/controller View View Group View Event listener/controller View View Group View View
94
System schedules apps and invokes app life cycle event handlers
System propagates UI events, and invokes UI view event handlers System Support App lifecycle callbacks/custom start pause … App View Group Event listener/controller View View Group View Event listener/controller View View Group View View
95
GUI Design/Implementation Points
App lifecycle callbacks/custom start pause … App View Group Event listener/controller View View Group View -How to specify the customized life cycle callbacks? Event listener/controller View View Group View View
96
GUI Design/Implementation Points
-How to define the view structure? App lifecycle callbacks/custom start pause … App View Group Event listener/controller View View Group View -How to specify the customized life cycle callbacks? Event listener/controller View View Group View View
97
GUI Design/Implementation Points
-How to define the view structure? App lifecycle callbacks/custom start pause … App View Group Event listener/controller View View Group View -How to specify the customized life cycle callbacks? Event listener/controller View View Group -How to specify the callbacks for a view? View View
98
GUI Design/Implementation Points
-How to define the view structure? App lifecycle callbacks/custom start pause … Data/Model App View Group Event listener/controller View View Group View -How to specify app-specific life-cycle handlers? Event listener/controller View View Group -How to link the callbacks defined in a view to listener/controller? View View
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.