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

Slides:



Advertisements
Similar presentations
Android Application Development Tutorial. Topics Lecture 6 Overview Programming Tutorial 3: Sending/Receiving SMS Messages.
Advertisements

Cosc 5/4730 Android Services. What is a service? From android developer web pages: Most confusion about the Service class actually revolves around what.
All About Android Introduction to Android 1. Creating a New App “These aren’t the droids we’re looking for.” Obi-wan Kenobi 1. Bring up Eclipse. 2. Click.
Application Fundamentals. See: developer.android.com/guide/developing/building/index.html.
Android 101 Application Fundamentals January 29, 2010.
Mobile Programming Pertemuan 6 Presented by Mulyono Poltek NSC Surabaya.
@2011 Mihail L. Sichitiu1 Android Introduction Application Fundamentals.
1 Android: Event Handler Blocking, Android Inter-Thread, Process Communications 10/11/2012 Y. Richard Yang.
1 Mobile Software Development Framework: Android Activity, View/ViewGroup, External Resources, Listener 10/9/2012 Y. Richard Yang.
© Keren Kalif Intro to Android Development Written by Keren Kalif, Edited by Liron Blecher Contains slides from Google I/O presentation.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Concurrency in Android with.
Software Architecture of Android Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.
Mobile Computing Lecture#08 IntentFilters & BroadcastReceivers.
Cosc 5/4730 Introduction: Threads, Android Activities, and MVC.
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.
Using Intents to Broadcast Events Intents Can be used to broadcast messages anonymously Between components via the sendBroadcast method As a result Broadcast.
COMP 365 Android Development.  Perform operations in the background  Services do not have a user interface (UI)  Can run without appearing on screen.
DUE Hello World on the Android Platform.
CS378 - Mobile Computing Intents.
16 Services and Broadcast Receivers CSNB544 Mobile Application Development Thanks to Utexas Austin.
1 Announcements Homework #2 due Feb 7 at 1:30pm Submit the entire Eclipse project in Blackboard Please fill out the when2meets when your Project Manager.
1 Mobile Software Development Framework: Android 2/28/2011 Y. Richard Yang.
Threads and Services. Background Processes One of the key differences between Android and iPhone is the ability to run things in the background on Android.
Programming Handheld and Mobile devices 1 Programming of Handheld and Mobile Devices Lecture 13 lcdui and OXO Rob Pooley
CS378 - Mobile Computing Intents. Allow us to use applications and components that are part of Android System – start activities – start services – deliver.
Services A Service is an application component that can perform long-running operations in the background and does not provide a user interface. An application.
Services 1 CS440. What is a Service?  Component that runs on background  Context.startService(), asks the system to schedule work for the service, to.
Announcements Homework #2 will be posted after class due Thursday Feb 7, 1:30pm you may work with one other person No office hours tonight (sorry!) I will.
Android Boot Camp Demo Application – Part 1. Development Environment Set Up Download and install Java Development Kit (JDK) Download and unzip Android.
1 Mobile Software Development Framework: Android Inter- Thread, Process Communications 10/11/2012 Y. Richard Yang.
HW#9 Clues CSCI 571 Fall, HW#9 Prototype
Activities and Intents Richard S. Stansbury 2015.
Recap of Part 1 Terminology Windows FormsAndroidMVP FormActivityView? ControlViewView? ?ServiceModel? Activities Views / ViewGroups Intents Services.
Services Background operating component without a visual interface Running in the background indefinitely Differently from Activity, Service in Android.
1 Mobile Software Development Framework: IOS 10/2/2012 Y. Richard Yang.
1 Introduction to J2ME Outline MIDP Building J2ME Apps- Tool J2ME Wireless Toolkit Demo MIDlet Programming -- MIDlet Transition States -- Midlet Skeleton.
Lecture 2: Android Concepts
Lecture 6: Process and Threads Topics: Process, Threads, Worker Thread, Async Task Date: Mar 1, 2016.
Speech Service & client(Activity) 오지영.
Mobile Programming Lecture 4 Resources, Selection, Activities, Intents.
Intents and Broadcast Receivers Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution.
Services. What is a Service? A Service is not a separate process. A Service is not a thread. A Service itself is actually very simple, providing two main.
The Ingredients of Android Applications. A simple application in a process In a classical programming environment, the OS would load the program code.
Developing Android Services. Objectives Creating a service that runs in background Performing long-running tasks in a separate thread Performing repeated.
1 Mobile Application Development Framework 4/16/2009 Richard Yang.
CS371m - Mobile Computing Intents 1. Allow us to use applications and components that are already part of Android System – start activities – start services.
Concurrency in Android
CS434/534: Topics in Networked (Networking) Systems Mobile System: Android (Single App/Process) Yang (Richard) Yang Computer Science Department Yale.
Intents and Broadcast Receivers
Lecture 2: Android Concepts
Android Application Development 1 6 May 2018
Broadcast receivers.
CS371m - Mobile Computing Services and Broadcast Receivers
Instructor: Mazhar Hussain
Mobile Software Development Framework: Android Activity, View/ViewGroup, External Resources, Handler/ASyncTask 10/9/2012 Y. Richard Yang.
Android – Event Handling
ITEC535 – Mobile Programming
Reactive Android Development
Mobile Software Development Framework: Android
Android Application Development android.cs.uchicago.edu
Developing Android Services
Mobile Software Development Framework: Android
Android Topics UI Thread and Limited processing resources
Android Topics Asynchronous Callsbacks
Activities and Intents
Android Developer Fundamentals V2
Android Developer Fundamentals V2 Lesson 5
Threads, Handlers, and AsyncTasks
Lecture 2: Android Concepts
Presentation transcript:

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

2 Admin. r Homework 2 due today m Please schedule time to meet with the TA to demo your program r Midterm: Wednesday after spring break

3 Recap: Mobile Programming Requirements m Handle heterogeneous devices/configurations m Be extremely efficiency on using resources (memory, battery, …) m Easy programming for event-driven programming m …

Recap: tinyOS r Customized OS for each app. r Reusability achieved through m Components and interfaces structure r Execution model: two threads m One for tasks m One for event handling 4

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 Recap: J2ME r Scale down a popular programming environment to ease learning r Use virtual machines to mask device heterogeneity r Use configuration/profile to handle device heterogeneity to avoid using lowest common denominator r MIDLet and Displayable to support user-interface driven applications m MIDLet manages app life cycle m Displayable has commands and provides command listener r Introduce persistent record store

Recap: Android r Scale down a popular programming environment to ease learning r Use virtual machines to mask device heterogeneity r Activity and View

Activity r A screen with which users can interact r Activity has life cycle to yield resources 8

View r A view component is a building block for user interface components. r Widget Toolbox m TextView, EditText, Button, Form, TimePicker… m ListView m Layout Positions of controls LinearLayout, Relativelayout

View by XML r Layout of visual interface r Java Code m Initialize m Access TextView myTextView = (TextView)findViewById(R.id.myTextVie w); <LinearLayout xmlns:android=” /apk/res/android” android:orientation=”vertical” android:layout_width=”fill_parent” android:layout_height=”fill_parent”> <TextView android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:text=”Hello World, HelloWorld” public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); } main.xml

User Interaction Event r onKeyDown. onKeyUp r onTrackBallEvent r onTouchEvent 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; }}); } registerButton.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) {….}}

Example: TipCal 12

Application Framework (Android): Key Concepts r Activity and view m Visible screen for user interaction r External resources 13

External Resources 14

Application Framework (Android): Key Concepts r Activity and view m Visible screen for user interaction r External resources r Service 15

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).

Application Framework (Android): Key Concepts r Activity and view m Visible screen for user interaction r External resources r Service r Intercommunications 17 App Communication among apps: - Intent - broadcast - data provider

Application and Component Glues r Intent m An intent is an abstract description of an operation to be performed. m To invoke operations from your own or others m Can pass data back and forth between app. r Intent Filter m Register Activities, Services, and Broadcast Receivers as being capable of performing an action on a particular kind of data.

Intent Description m m Action m Data m Category, e.g., LAUNCHER 19

Intent Usage r Pass to Context.startActivity() or Activity.startActivityForResult() to launch an activity or get an existing activity to do something new.Context.startActivity() Activity.startActivityForResult() r Pass to Context.startService() to initiate a service or deliver new instructions to an ongoing service.Context.startService() m 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.Context.bindService() r 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. Context.sendBroadcast()Context.sendOrderedBroadcast() Context.sendStickyBroadcast() 20

Android: Broadcast Receiver r Sending a broadcast: m Context.sendBroadcast(Intent intent, String receiverPermission) m Context.sendOrderedBroadcast() r Receiving broadcast: m Intent registerReceiver (BroadcastReceiver receiver, IntentFilter filter) 21

Intent Resolution: Explicit r Explicit intents: component identified 22 r Make sure AndroidManifest.xml announces activities to be started Intent myIntent = new Intent(IntentController.this, TipCal.class); startActivity(myIntent); <activity android:name=".IntentController" android:label="Intent1">

Intent Resolution: Implicit r Implicit intents m System matches an intent object to the intent filters of others 23

Intent filter 24 action category data

Intent Example II: Implicit r AndroidManifest.xml file for com.android.browser 25 String action = "android.intent.action.VIEW"; Uri data = Uri.parse(" Intent myIntent = new Intent(action, data); startActivity(myIntent);

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

A Design Template: Invoker 27 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);

A Design Template: Provider 28 r For more complex data passing, please read the tutorial

A Design Template: Provider 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(); }

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

Intent and Broadcast: Receiver 31

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

r See CS434 broadcast receiver examples 33

Service r Extends Service, providing m onStartCommand()The system calls this method when another component, such as an activity, requests that the service be started, by callingstartService(). Once this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService(). (If you only want to provide binding, you don't need to implement this method.)onBind()The system calls this method when another component wants to bind with the service (such as to perform RPC), by callingbindService(). In your implementation of this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder. You must always implement this method, but if you don't want to allow binding, then you should return null.onCreate()The system calls this method when the service is first created, to perform one-time setup procedures (before it calls eitheronStartCommand() or onBind()). If the service is already running, this method is not called.onDestroy()The system calls this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc. This is the last call the service receives. 34

Rules r Notify users r Background processing 35

Problem: Booking May Take a Long Time 36 r ANRs (Application not responding) happen when m Main thread (“event”/UI) does not respond to input in 5 sec m A broadcast receiver does not finish in 10 sec r 5-10 sec is absolute upper bound

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

Rules r Notify users r Background processing 38

Background Processing r Problem: 39

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); [... ] } 40

public class MyActivity extends Activity { 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 [... ] } } 41

Tools: AsyncTask 42 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!

Tools: android.app.IntentService r An abstract Service m serializes the handling of the Intents passed upon service start m to use this class, extend it and implement onHandleIntent(Intent). m the Service will automatically be stopped when the last enqueued Intent is handled r All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time. 43

Example: Calendar's use of IntentService public class DismissAllAlarmsService extends IntentService public void onHandleIntent(Intent unusedIntent) { ContentResolver resolver = getContentResolver();... resolver.update(uri, values, selection, null); } in AlertReceiver extends BroadcastReceiver, onReceive(): (main thread) Intent intent = new Intent(context, DismissAllAlarmsService.class); context.startService(intent); 44