700 likes | 921 Vues
Android Development - 2. Prabhaker Mateti. Agenda. Android.os classes, debug java.io refresher Activities and Tasks Processes and Threads Android Location Service Google Maps External Library Code Example: SimpleNetworking Code Example: Android Location Service.
E N D
Android Development - 2 PrabhakerMateti
Agenda Android.os classes, debug java.io refresher Activities and Tasks Processes and Threads Android Location Service Google Maps External Library Code Example: SimpleNetworking Code Example: Android Location Service
android.os interfaces Provides basic operating system services, message passing, and inter-process communication on the device. Handler.Callback Ibinder interface for a remotable object RPC IBinder.DeathRecipient Iinterface Base class for Binder interfaces. Parcelable cf. serializable, marshalled result RecoverySystem.ProgressListener
android.os classes AsyncTask<Params, Progress, Result> enables proper use of the UI thread. BatteryManager Binderremotable object; RPC mechanism defined by IBinder. Bundle A mapping from values to Parcelable types. ConditionVariable a locking paradigm. Environment MemoryFile wrapper for the Linux ashmem (Anonymous SHaredMEMory) driver.
android.os classes Parcel Container for a message (data and object references) that can be sent through an IBinder. PatternMatcher A simple pattern matcher; not full reg-exp, only simple globbing. RecoverySystem the separate partition that can be used to install system updates, wipe user data, etc. StrictMode while developing …
android.os.Debug debugging functions for Android applications, including tracing and allocation counts. startMethodTracing(StringtraceName, intbufferSize, int flags) dumpService (String name, FileDescriptorfd, String[]args) getMemoryInfo (Debug.MemoryInfomemoryInfo) threadCpuTimeNanos ()
java.io.FileOutputStream public FileOutputStream (Filefile, boolean append) public void write (byte[] buffer, int offset, intbyteCount) public void close () BufferedOutputStream
java.io.FileInputStream FileInputStream(String path) Equivalent to new FileInputStream(new File(path)). public int read (byte[] buffer, int offset, intbyteCount) public void close () BufferedInputStream.
Application Components • 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.
package android.widget 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
Live Wallpapers similar to a regular Android service. consumes CPU time, memory, battery onCreateEngine() whose goal is to create a WallpaperService.Engine. source code example: android-sdk-linux_x86/ docs/resources/samples/CubeLiveWallpaper
Activity • An Activity is an application component that provides a UI screen • e.g., dial the phone, take a photo, send an email, 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
Activities One activity can start another, including one defined in a different application. Context.startActivity(Intent) Activity.startActivityForResult (Intent, Request_Code) Asynchronous Message (Intent)
public abstract class Context • extends java.lang.Object • Interface to global information about an application environment. • implementation is provided by the Android system. • Selected methods • File getExternalFilesDir(String type) • FileOutputStreamopenFileOutput(String name, int mode) • Intent registerReceiver (BroadcastReceiver, IntentFilter, String broadcastPermission, Handler scheduler) • void sendBroadcast(Intent intent, String receiverPermission) • void startActivities(Intent[] intents) • Object getSystemService(String name) • ComponentNamestartService(Intent service)
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”
android.os.Process public static final int FIRST_APPLICATION_UID public Process () public static final void killProcess (intpid) public static final void sendSignal (intpid, int signal) public static final intgetThreadPriority (inttid) public static final void setThreadPriority (int priority)
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.
Processes • We can specify a process where an individual component should run by setting a process name to “process” attribute of <activity>, <service>, <receiver>, or <provider>. • 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 <application>.
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)
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.Looperfor 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.
Thread Issues • If the UI thread is blocked for more than a few seconds • "application not responding" (ANR) dialog • 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
AsyncTask • 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 AsyncTask • implement the doInBackground() • runs in a pool of background threads. • implement onPostExecute(), which delivers the result from the above and runs in the UI thread • run the taskA by calling execute() from the UI thread.
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
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.
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 with • a Service that's bound to the activity that the user is interacting with. • a Service that has called startForeground(). • a Service that's executing one of onCreate(), onStart(), or onDestroy(). • a BroadcastReceiver that's executing its onReceive() method. • 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.
Visible process • 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). • a Service that's bound to a visible (or foreground) activity. • A visible process is considered extremely important and will not be killed unless doing so is required to keep all foreground processes running.
Service process 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. 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.
Background process A process holding an activity that's not currently visible to the user (the activity's onStop() method has been called). 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.
Empty process 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.
Activities and Tasks Application1 (.apk) Application2 (.apk) Process Process Activity Activity Activity Activity Activity Activity Activity Activity Content Provider Content Provider Service Service Service Service A task is a collection of related Activities. It is capable of spanning multiple processes.
Activities and Tasks Instance of Activity B The one that's currently running Instance of Activity C Instance of Activity B Instance of Activity A The one that began the task (typically, an activity the user selected in the application launcher) A Stack • 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.
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().
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.
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 …
Launch Mode Differences-1 Original Task Original Task New Task New Activity Activity A Activity A Root Activity Root Activity New Activity standard/singleTop without FLAG_ACTIVITY_NEW_TASK singleTask/singleInstance Which task will hold the activity that responds to the intent
Launch Mode Differences-2 Task A Task B Task A Task B Activity B Activity C Activity B Activity C Activity B Activity A Activity A Activity D Activity C Activity B and Activity C are standard/singleTop Activity C is singleTask or singleInstance • 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.
Launch Mode Differences-3 Whether the instance can have other activities in its task
Launch Mode Differences-4a Activity D The existing instance D is expected to handle the new intent (since it's at the top of the stack) Activity D Activity D Activity D An intent arrives for an activity of type D Activity C Activity C Activity C Activity B Activity B Activity B Activity A Activity A Activity A Original Task If D is"standard" If D is"singleTop" Whether a new instance of the class will be launched to handle a new intent
Launch Mode Differences-4b Activity B Activity B Activity D Activity D Activity D An intent arrives for an activity of type B The existing instance B is not expected to handle the new intent (since it's not at the top of the stack) Activity C Activity C Activity C Activity B Activity B Activity B Activity A Activity A Activity A Original Task If B is"standard" If B is"singleTop" Whether a new instance of the class will be launched to handle a new intent (Cont)
Launch Mode Differences-4c A "singleInstance" activity is always at the top of the stack, so it is always in position to handle the intent. An intent arrives for an activity of type B Activity B Activity B Original Task If B is"singleInstance" Whether a new instance of the class will be launched to handle a new intent (Cont)
Launch Mode Differences-4d Activity B Activity B Activity B can handle the intent since it is in position. An intent arrives for an activity of type B Activity A Activity A Original Task If B is"singleTask" Activity A Activity A Activity B cannot handle the intent since it is not in position and the intent is dropped. An intent arrives for an activity of type B Activity B Activity B Original Task If B is"singleTask" Whether a new instance of the class will be launched to handle a new intent (Cont)
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.
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.
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.
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
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.
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()
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.