Presentation is loading. Please wait.

Presentation is loading. Please wait.

Android Development - 2 Prabhaker Mateti CEG436: Mobile Computing (PM) 1.

Similar presentations


Presentation on theme: "Android Development - 2 Prabhaker Mateti CEG436: Mobile Computing (PM) 1."— Presentation transcript:

1 Android Development - 2 Prabhaker Mateti CEG436: Mobile Computing (PM) 1

2 Android.os classes, debug java.io refresher Activities and Tasks Processes and Threads Android Location Service Google Maps External Library Code Example: SimpleNetworkingSimpleNetworking Code Example: Android Location ServiceAndroid Location Service Agenda CEG436: Mobile Computing (PM)2

3 Provides basic operating system services, message passing, and inter-process communication on the device. Handler.Callback Ibinder interface for a remotable object RPC Ibinder IBinder.DeathRecipient Iinterface Base class for Binder interfaces. Iinterface Parcelable cf. serializable, marshalled result Parcelable RecoverySystem.ProgressListener android.os interfaces CEG436: Mobile Computing (PM)3

4 AsyncTask enables proper use of the UI thread. AsyncTask BatteryManager Binder remotable object; RPC mechanism defined by IBinder. Binder IBinder Bundle A mapping from values to Parcelable types. Bundle ConditionVariable a locking paradigm. ConditionVariable Environment MemoryFile wrapper for the Linux ashmem (Anonymous SHared MEMory) driver. MemoryFile android.os classes CEG436: Mobile Computing (PM)4

5 Parcel Container for a message (data and object references) that can be sent through an IBinder. Parcel PatternMatcher A simple pattern matcher; not full reg-exp, only simple globbing. PatternMatcher RecoverySystem the separate partition that can be used to install system updates, wipe user data, etc. RecoverySystem StrictMode while developing … StrictMode android.os classes CEG436: Mobile Computing (PM)5

6 debugging functions for Android applications, including tracing and allocation counts. startMethodTracing(String traceName, int bufferSize, int flags) startMethodTracingString dumpService (String name, FileDescriptor fd, String[] args)StringFileDescriptor String[] getMemoryInfo (Debug.MemoryInfo memoryInfo)Debug.MemoryInfo threadCpuTimeNanos () android.os.Debug CEG436: Mobile Computing (PM)6

7 public FileOutputStream (File file, boolean append)File public void write (byte[] buffer, int offset, int byteCount) public void close () BufferedOutputStream java.io.FileOutputStream CEG436: Mobile Computing (PM)7

8 FileInputStream(String path) Equivalent to new FileInputStream(new File(path)). FileInputStreamString public int read (byte[] buffer, int offset, int byteCount) public void close () BufferedInputStream. BufferedInputStream java.io.FileInputStream CEG436: Mobile Computing (PM)8

9 Activity – represents a single screen with a user interface. Service – runs in the background; Long-running; for remote processes – no user interface. Content provider – manages a shared set of application data. Broadcast receiver – responds to broadcast announcements. An application can have multiple instances of the above four types. Each component is a different point through which the system can enter an application. Every component has a managed lifecycle. Application Components CEG4369

10 App Widgets are miniature application views that can be embedded in other applications (such as the Home screen) and receive periodic updates. App Widgets provide users access to some of your application features directly from the Home screen (without the need to launch an activity) App Widgets are backed by a special kind of broadcast receiver that handles the App Widget lifecycle package android.widget CEG436: Mobile Computing (PM)10

11 similar to a regular Android service. consumes CPU time, memory, battery onCreateEngine() whose goal is to create a WallpaperService.Engine. onCreateEngine() WallpaperService.Engine. source code example: android-sdk-linux_x86/ docs/resources/samples/CubeLiveWallpaper Live Wallpapers CEG436: Mobile Computing (PM)11

12 Activity An Activity is an application component that provides a UI screenActivity – e.g., dial the phone, take a photo, send an , or view a map. Each activity is given a window. – typically fills the screen, but – may be smaller than the screen – float on top of other windows CEG436: Mobile Computing (PM)12

13 Activities One activity can start another, including one defined in a different application. Context.startActivity(Intent) Activity.startActivityForResult (Intent, Request_Code) Asynchronous Message (Intent) CEG436: Mobile Computing (PM)13

14 extends java.lang.Objectjava.lang.Object – Interface to global information about an application environment. – implementation is provided by the Android system. Selected methods 1.File getExternalFilesDir(String type) 2.FileOutputStream openFileOutput(String name, int mode) 3.Intent registerReceiver (BroadcastReceiver, IntentFilter, String broadcastPermission, Handler scheduler) 4.void sendBroadcast(Intent intent, String receiverPermission) 5.void startActivities(Intent[] intents) 6.Object getSystemService(String name) 7.ComponentName startService(Intent service) public abstract class Context CEG436: Mobile Computing (PM)14

15 Activities vs Tasks (Apps) A concrete class in the API An encapsulation of a particular operation They run in the process of the.apk which installed them Optionally associated with a window (UI) Have an execution Context More of a notion than a concrete API entity A collection of related Activities Capable of spanning multiple processes Associated with their own UI history stack What users on other platforms know as “applications” CEG436: Mobile Computing (PM) 15

16 public static final int FIRST_APPLICATION_UID public Process () public static final void killProcess (int pid) public static final void sendSignal (int pid, int signal) public static final int getThreadPriority (int tid) public static final void setThreadPriority (int priority) android.os.Process CEG436: Mobile Computing (PM)16

17 Processes When the first of an application's components needs to be run, Android starts a Linux process for it with a single thread of execution (Main Thread). Android may decide to kill a process to reclaim resources. CEG436: Mobile Computing (PM)17

18 Processes We can specify a process where an individual component should run by setting a process name to “process” attribute of,,, or. – Each component can run in its own process. – Some components share a process while others do not. – Components of different applications also can run in the same process. We can set a default value that applies to all components by setting a default process to “process” attribute of. CEG436: Mobile Computing (PM)18

19 Main Thread All components are instantiated in the main thread (aka UI thread) of the specified process. System calls to the components are dispatched from the main thread. Methods that respond to those calls always run in the main thread of the process. Main thread components should not perform long or blocking operations (e.g., network downloads, heavy computation loops) CEG436: Mobile Computing (PM)19

20 Worker Threads Anything that may not be completed quickly should be assigned to a different thread. Threads are created in code using standard Java Thread objects. android.os.Looper for running a message loop within a thread android.os.Handler for processing messages android.os.HandlerThread for starting a new thread that has a looper. CEG436: Mobile Computing (PM)20

21 If the UI thread is blocked for more than a few seconds – "application not responding" (ANR) dialogapplication not responding Andoid UI toolkit is not thread-safe. Two rules to follow: – Do not block the UI thread – Do not access the Android UI toolkit from outside the UI thread Thread Issues CEG436: Mobile Computing (PM)21

22 Perform asynchronous work on user interface. – Does the blocking operations in a worker thread and then publishes the results on the UI thread, – without requiring you to handle threads and/or handlers yourself. taskA extends AsyncTaskAsyncTask implement the doInBackground()doInBackground() – runs in a pool of background threads. – implement onPostExecute(), which delivers the result from the above and runs in the UI threadonPostExecute() run the taskA by calling execute() from the UI thread.execute() AsyncTask CEG436: Mobile Computing (PM)22

23 Linux v Android Process Basics Android process == Linux process – w/ its own unique UID By default, 1 process per.apk By default, 1 thread per process Most components interleave events into the main thread CEG436: Mobile Computing (PM)23

24 Process Lifecycles Android tries to maintain a process for as long as possible, but eventually it may have to remove some processes when memory runs low. To determine candidates to be killed, Android places each process into an "importance hierarchy“ of 5 levels based on the components running in it and the state of those components. CEG436: Mobile Computing (PM)24

25 Foreground process A process that is required for what the user is currently doing. A process is considered to be in the foreground if it hosts: – an Activity that the user is interacting withActivity – a Service that's bound to the activity that the user is interacting with.Service – a Service that has called startForeground().ServicestartForeground() – a Service that's executing one of onCreate(), onStart(), or onDestroy().ServiceonCreate()onStart()onDestroy() – a BroadcastReceiver that's executing its onReceive() method.BroadcastReceiveronReceive() Generally, only a few foreground processes exist at any given time. – They are killed only as a last resort—if memory is so low that they cannot all continue to run. – Generally, at that point, the device has reached such a state that killing some foreground processes is required to keep the user interface responsive. CEG436: Mobile Computing (PM)25

26 A process that does not have any foreground components, but still can affect what the user sees on screen. A process is considered visible if it hosts: – an Activity that is not in the foreground, but is still visible to the user (its onPause() method has been called).ActivityonPause() – a Service that's bound to a visible (or foreground) activity.Service A visible process is considered extremely important and will not be killed unless doing so is required to keep all foreground processes running. Visible process CEG436: Mobile Computing (PM)26

27 A process that is running a service that has been started with the startService() method and does not fall into either of the two higher categories.startService() Service processes are not directly tied to anything the user sees. However, they are generally doing things that the user cares about (such as playing music in the background or downloading data on the network), so the system keeps them running unless there's not enough memory to retain them along with all foreground and visible processes. Service process CEG436: Mobile Computing (PM)27

28 A process holding an activity that's not currently visible to the user (the activity's onStop() method has been called).onStop() These processes have no direct impact on the user experience, and the system can kill them at any time to reclaim memory for a foreground, visible, or service process. Usually there are many background processes running, so they are kept in an LRU (least recently used) list to ensure that the process with the activity that was most recently seen by the user is the last to be killed. If an activity implements its lifecycle methods correctly, and saves its current state, killing its process will not have a visible effect on the user experience, because when the user navigates back to the activity, the activity restores all of its visible state. Background process CEG436: Mobile Computing (PM)28

29 A process that doesn't hold any active application components. The only reason to keep this kind of process alive is for caching purposes, to improve startup time the next time a component needs to run in it. The system often kills these processes in order to balance overall system resources between process caches and the underlying kernel caches. Empty process CEG436: Mobile Computing (PM)29

30 Activities and Tasks A task is a collection of related Activities. It is capable of spanning multiple processes. Application1 (.apk) Process Activity Content Provider Service Application2 (.apk) Process Activity Content Provider Service CEG436: Mobile Computing (PM)30

31 Activities and Tasks All activities in a task are arranged in a stack. If one activity starts another, the new activity is pushed on the stack and it becomes the running activity. When the user presses the BACK key, the current activity is popped from the stack and the previous one resumes. Instance of Activity B Instance of Activity C Instance of Activity B Instance of Activity A A Stack The one that began the task (typically, an activity the user selected in the application launcher) The one that's currently running CEG436: Mobile Computing (PM)31

32 Affinities An affinity means a preference for each activity to belong to a certain task. An individual affinity can be set for each activity: By default, a new activity is launched into the task of the activity that called startActivity(). CEG436: Mobile Computing (PM)32

33 Affinities If the Intent object passed to startActivity() contains the FLAG_ACTIVITY_NEW_TASK flag, – If there's already an existing task with the same affinity as the new activity, the activity is launched into that task. – If not, it begins a new task. allowTaskReparenting == true  it can move from the task it starts in to the task it has an affinity for when that task comes to the fore. CEG436: Mobile Computing (PM)33

34 Launch Modes standard (default) singleTop singleTask singleInstance A launch mode can be set for each activity The modes differ from each other on four points … CEG436: Mobile Computing (PM)34

35 Launch Mode Differences-1 Which task will hold the activity that responds to the intent New Activity Activity A Root Activity Original Task Activity A Root Activity Original Task New Activity New Task standard/singleTop without FLAG_ACTIVITY_NEW_TASK singleTask/singleInstance CEG436: Mobile Computing (PM)35

36 Launch Mode Differences-2 Whether there can be multiple instances of the activity A "standard" or "singleTop" activity can be instantiated many times. A "singleTask" or "singleInstance" activity is limited to just one instance. Activity B Activity A Task A Activity D Task B Activity B and Activity C are standard/singleTop Activity C Activity B Activity C Activity B Activity A Task A Activity C Task B Activity C is singleTask or singleInstance CEG436: Mobile Computing (PM)36

37 Launch Mode Differences-3 Whether the instance can have other activities in its task "standard" These modes permit multiple activities to belong to the task. A "singleTask" activity will always be the root activity of the task. "singleTop" "singleTask" "singleInstance" An activity stands alone as the only activity in its task. CEG436: Mobile Computing (PM)37

38 Launch Mode Differences-4a Whether a new instance of the class will be launched to handle a new intent Original Task Activity B Activity A Activity C Activity D An intent arrives for an activity of type D Activity B Activity A Activity C Activity D If D is"standard" Activity B Activity A Activity C Activity D If D is"singleTop" The existing instance D is expected to handle the new intent (since it's at the top of the stack) CEG436: Mobile Computing (PM)38

39 Launch Mode Differences-4b Whether a new instance of the class will be launched to handle a new intent (Cont) Original Task The existing instance B is not expected to handle the new intent (since it's not at the top of the stack) Activity B Activity A Activity C Activity D An intent arrives for an activity of type B Activity B Activity A Activity C Activity D If B is"standard" Activity B Activity A Activity C Activity D If B is"singleTop" Activity B CEG436: Mobile Computing (PM)39

40 Launch Mode Differences-4c Whether a new instance of the class will be launched to handle a new intent (Cont) Activity B Original Task An intent arrives for an activity of type B If B is"singleInstance" A "singleInstance" activity is always at the top of the stack, so it is always in position to handle the intent. Activity B CEG436: Mobile Computing (PM)40

41 Launch Mode Differences-4d Whether a new instance of the class will be launched to handle a new intent (Cont) Activity B Original Task An intent arrives for an activity of type B If B is"singleTask" Activity B can handle the intent since it is in position. Activity B Activity A Activity B Original Task An intent arrives for an activity of type B If B is"singleTask" Activity B cannot handle the intent since it is not in position and the intent is dropped. Activity B Activity A CEG436: Mobile Computing (PM)41

42 Clearing the Stack Default Control – If the user leaves a task for a long time, the system clears the task of all activities except the root activity. If alwaysRetainTaskState is set to the root activity – The task retains all activities in its stack even after a long period. If clearTaskOnLaunch is set to the root activity – The stack is cleared down to the root activity whenever the user leaves the task and returns to it. – The user always returns to the task in its initial state, even after a momentary absence. CEG436: Mobile Computing (PM)42

43 Clearing the Stack If finishOnTaskLaunch is set to an activity of a task – The activity remains part of the task only for the current session. – If the user leaves and then returns to the task, it is no longer present. If an intent includes the FLAG_ACTIVITY_CLEAR_TOP flag and the target task already has an instance of the type of activity that should handle the intent in its stack, all activities above that instance are cleared away. CEG436: Mobile Computing (PM)43

44 Activity Lifecycle Running state: An activity is in the foreground of the screen (at the top of the activity stack for the current task). Paused state: An activity has lost focus but is still visible to the user. Stopped state: An activity is completely obscured by another activity. – It still retains all state and member information. If an activity is paused or stopped, the system can drop it from memory either by: – asking it to finish (calling its finish() method) – simply killing its process. CEG436: Mobile Computing (PM)44

45 Activity Lifecycle onCreate() – when the activity is first created, or – when the activity was killed onStart() – just before the activity becomes visible to user onRestart() – after the activity has been stopped, just prior to it being started again onResume() – just before the activity starts interacting with the user – At this point, the activity is at the top of the activity stack, with user input going to it. onPause() – when the system is about to start resuming another activity – This method is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, and so on. onStop() – when the activity is no longer visible to the user – This may happen because it is being destroyed, or because another activity has been resumed and is covering it. onDestroy() – Called before the activity is destroyed CEG436: Mobile Computing (PM) 45

46 Activity Lifecycle Three nested loops for the entire lifecycle Visible Lifetime – During this time, the user can see the activity on screen – onStart() and onStop() can be called multiple times, as the activity alternates between being visible and hidden to the user. Foreground Lifetime – During this time, the activity is in front of all other activities on screen and is interacting with the user. CEG436: Mobile Computing (PM)46

47 Saving activity state CEG436: Mobile Computing (PM)47

48 Service Lifecycle CEG436: Mobile Computing (PM) 48

49 Service Lifecycle The service is started by calling – Context.startService() Runs until someone, including itself, calls – Context.stopService() Clients establish a connection to the Service object and use that connection to call into the service. – established by Context.bindService() – closed by Context.unbindService() CEG436: Mobile Computing (PM)49

50 Broadcast Receiver Lifecycle Only single callback method onReceive(currentContext, Intent broadcastMsg) When a broadcast message arrives for the receiver, Android calls the method and passes it the Intent object containing the message. A process with an active broadcast receiver is protected from being killed but a process with only inactive components can be killed by the system at any time. CEG436: Mobile Computing (PM)50

51 Android Location Service CEG436: Mobile Computing (PM) 51

52 Determining User Location Multitude of location sources GPS, Cell-ID, and Wi-Fi can each provide a clue to users location. Determining which to use and trust is a matter of trade-offs in accuracy, speed, and battery-efficiency. User movement Account for movement by re- estimating user location every so often. Varying accuracy Location estimates coming from each location source are not consistent in their accuracy. A location obtained 10 seconds ago from one source might be more accurate than the newest location from another or same source. CEG436: Mobile Computing (PM)52

53 android.location Address A class representing an Address, i.e, a set of Strings describing a location. Address Geocoder A class for handling geocoding and reverse geocoding. Geocoder GpsStatus.NmeaListener Used for receiving NMEA sentences from the GPS. GpsStatus.NmeaListener LocationManager This class provides access to the system location services. LocationManager For more information, read the guide to Obtaining User Location. Obtaining User Location CEG436: Mobile Computing (PM)53

54 android.location.LocationManager LocationManager lcm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); listener = new LocationListener() { … } lcm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, a, b, listener); – NETWORK_PROVIDER == cell phone tower and Wi-Fi – GPS_PROVIDER – a == minimum time interval between notifications; 0 is ok – b == minimum change in distance between notifications; 0 is ok public void onLocationChanged(Location ltn) { makeUseOfNewLocation(ltn);// your method } public void onStatusChanged(String provider, int status, Bundle extras) {…} public void onProviderEnabled(String provider) {…} public void onProviderDisabled(String provider) {…} CEG436: Mobile Computing (PM)54

55 Location Use Model for Performance CEG436: Mobile Computing (PM) 55

56 Location Trade-Offs Long windows of listening for location fixes can consume a lot of battery power, but short periods might not allow for sufficient accuracy. locationManager.removeUpdates(listener); locationManager.getLastKnownLocation(pro); The most recent fix is not always the best. – Choose location fixes based on several criteria. CEG436: Mobile Computing (PM)56

57 Tagging content with location CEG436: Mobile Computing (PM) 57

58 Help decide where to go CEG436: Mobile Computing (PM) 58

59 Providing Mock Location Data Eclipse – Window > Show View > Other > Emulator Control DDMS – Using the Emulator Console send coordinates: geo fix geo nmea $GPRMC,… – Use a GPX file describing a route for playback. – Use a KML file describing individual place marks. CEG436: Mobile Computing (PM)59

60 geocoding Geocoder gcd = new Geocoder( context, Locale. getDefault()); List addresses = gcd. getFromLocation(latit, longi, 1); if (addresses.size() > 0) System.out.println( addresses.get(0).getLocality()); CEG436: Mobile Computing (PM)60

61 GPS CEG436: Mobile Computing (PM)61

62 com.google.android.maps Set up a new Android project — or reconfigure an existing one — to build against the installed Google APIs add-on Set up a new Android project Set up an Android Virtual Device configuration that uses a the Google APIs add-on Set up an Android Virtual Device Add a uses-library element to your application's manifest file, to reference the Maps library. Add a uses-library element – Use the Maps classes in your application Get a Maps API Key, so that your application can display data from the Google Maps service. Get a Maps API Key Sign your application properly, using the certificate that matches your API Key. Sign your application properly Example: /add-ons/google_apis- /samples/MapsDemo Google Maps External Library CEG436: Mobile Computing (PM)62

63 Selected APIs CEG436: Mobile Computing (PM) 63

64 android.hardware Camera class is used to set image capture settings, start/stop preview, snap pictures, and retrieve frames for encoding for video. Camera GeomagneticField estimates magnetic field at a given point on Earth, and to compute the magnetic declination from true north. GeomagneticField Sensor Class representing a sensor. SensorEvent holds information such as the sensor's type, the time-stamp, accuracy and sensor's data. SensorManager lets you access the device's sensors. SensorSensorEventdataSensorManagersensors CEG436: Mobile Computing (PM)64

65 android.bluetooth BluetoothAdapter Represents the local Bluetooth radio. Entry-point for all Bluetooth interaction. Instantiate a BluetoothDevice using a known MAC address, and create a BluetoothServerSocket. BluetoothAdapterBluetoothDeviceBluetoothServerSocket BluetoothProfile.ServiceListener An interface for notifying BluetoothProfile IPC clients when they have been connected or disconnected to the service. BluetoothProfile.ServiceListener BluetoothSocket A connected or connecting Bluetooth socket. BluetoothSocket CEG436: Mobile Computing (PM)65

66 android.nfc NfcManager This is the high level manager, used to obtain this device's Near Field Communication (NFC) NfcAdapter. Acquire an instance: getSystemService(String) NfcManagerNfcAdaptergetSystemService(String) CEG436: Mobile Computing (PM)66

67 android.net ConnectivityManager Class that answers queries about the state of network connectivity. ConnectivityManager LocalSocketAddress A UNIX-domain (AF_LOCAL) socket address. LocalSocketAddress NetworkInfo Describes the status of a network interface of a given type (currently either Mobile or Wifi). NetworkInfo Uri.BuilderHelper class for building or manipulating URI references. Uri.Builder CEG436: Mobile Computing (PM)67

68 android.net.wifi WifiConfigurationA class representing a configured Wi-Fi network, including the security configuration. WifiConfiguration WifiManagerThis class provides the primary API for managing all aspects of Wi-Fi connectivity. WifiManager CEG436: Mobile Computing (PM)68

69 Device Administration DeviceAdminReceiver Can interpret raw intent actions that are sent by the system. DeviceAdminReceiver DevicePolicyManager manages policies for one or more DeviceAdminReceivers DevicePolicyManager DeviceAdminInfo specify metadata for a device administrator component. DeviceAdminInfo Device Administration API sample CEG436: Mobile Computing (PM)69

70 References CEG436: Mobile Computing (PM)70


Download ppt "Android Development - 2 Prabhaker Mateti CEG436: Mobile Computing (PM) 1."

Similar presentations


Ads by Google