You can telnet to your emulator, the port is in the title of your emulator (5554).
manipulate device while logged in :
network speed edge or network speed full or power capacity 5 or power status not-charging or geo fix 0.00 40.00 or sms send 301555555 "test msg" , see here for more:
metskem@athena ~ $ telnet localhost 5554
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Android Console: type 'help' for a list of commands
OK
help
Android console command help:
help|h|? print a list of commands
event simulate hardware events
geo Geo-location commands
gsm GSM related commands
cdma CDMA related commands
kill kill the emulator instance
network manage network settings
power power related commands
quit|exit quit control session
redir manage port redirections
sms SMS related commands
avd control virtual device execution
window manage emulator window
qemu QEMU-specific commands
sensor manage emulator sensors
try 'help <command>' for command-specific help
OK
you can run multiple emulators, and one let call the other, the number is equal to the port number again
Accessed by other resources as @string/string_name
Accessed in Java as R.string.string_name
res/layout/*.xml
Accessed by other resources as @layout/layout_name
Accessed in Java as R.layout.layout_name
Activity
The Activity Lifecycle:
Typical onCreate() workflow
Restore saved state (super.onCreate() )
Set content view
Initialize UI elements
Keep references to UI elements if necessary
Link UI elements to code actions
-- onRestart() , do specific stuff required after activity was stopped
-- onStart() , loading persistent application state
-- onResume() , start foreground-only actions
-- onPause() , shutdown foreground-only actions, save persistent stat
-- onStop() , cache state (may not be called when Android kills the activity)
-- onDestroy() , release activity resources (may not be called when Android kills the activity)
Activities are created by creating Intents, and passing these Intents to startActivity() or startActivityForResult() .
Started activity can set the result with Activity.setResult().
action - specifies the desired action (action_dial, action_edit, action_sync)
data - data associated with the intent, specified as a URI (Uri.parse("tel:0548512395")
category - additional info about components that can handle the intent (category_launcher or category_browser)
type - the mime type of the intent
component - the component that should receive the intent (always one activity)
extras - a Map of key-value pairs
flags - specify how intent should be handled, a few special flags: FLAG_ACTIVITY_NO_HISTORY (dont put activity in history stack) FLAG_DEBUG_LOG_RESOLUTION (extra logging when intent is processed)
Activity is a subclass of Context, so you can for example use new Intent(MyActivity.this, SecondActivity.class);
Two ways of Intent resolution:
explicit - the Intent has the "target" class name specified, the target Activity will be called directly
implicit - Android tries to match the Intent with the capabilities of the installed apps.
Implicit Intent resolution uses the following data of the Intent:
ACTION
DATA (URI and TYPE)
CATEGORY
Installed apps have intent-filters defined in their AndroidManifest.xml.
These filters can specify things like data, action, category and so on. If they want to react to implicit intents, they always have to specify the intent-filter category.DEFAULT.
If you want to know what's on your device (for example all intent filters) :
adb shell dumpsys package
Permissions
Android uses permissions to protect Resources, data and operations.
Applications can define their own permissions to protect their own resources (other apps are required to have those permissions). (permission tag)
And applications can define the permissions they use themselves (uses-permission).
There are application-level permissions and component-level permissions, the latter take precedence.
And we have :
Activity permissions (used when calling startActivity() or startActivityForResult()
Service permissions (used when calling stop/start/bindService()
broadcastreceiver permissions (restricts which components can send and receive broadcasts)
contentprovider permissions (restricts which components can read/write data in a content provider)
Fragments
Introduced in Android 3.0 to better support larger screens (Tablets).
Fragments represent a portion of a UI within an Activity => multi-pane activities.
A single Fragment can be used across multiple activities.
The lifecycle of a Fragment is coordinated with the lifecycle of an Activity, but they also have their own lifecycle callbacks.
Fragment lifecycle states :
resumed - visible in running activity
paused - another activity is in the foreground and has focus, the containing activity is visible
stopped - the fragment is not visible
Fragment callbacks :
onAttach() - activity created
onCreate() - ...
onCreateView() - fragment sets up and returns a view
onActivityCreated() - containing activity has completed onCreate() and the fragment has been installed
onResume() - similar to activity
onStart() - similar to activity
onPause() - similar to activity
onStop() - similar to activity
onDestroyView() -
onDestroy() - release resources
onDetach() - null out refs to hosting Activity
Statically add Fragment to Activity by specifying them in the layout file, or programmatically using the FragmentManager.
The View is the place and the means to exchange information between the user and the Application.
View is the key building block. It occupies a rectangular space on the screen, they are responsible for drawing themselves and handling events.
Predefined Views:
Button simple button to perform some action
ToggleButton - checked/not-checked state, light indicator showing state
Checkbox - another kind of 2-state button
RatingBar - row of stars
AutoCompleteTextView - an editable text field that provides completion suggestions as you type text
Common View operations:
set visibility
set checked state
set listeners
set props like background, opacity, orientation
manage input focus
View Listener Interfaces:
OnClickListener
OnLongClicklistener
OnFocusChanged
OnKeyListener
many more...
Displaying Views
Views are organized as a tree, Views with child Views
Android walks the View tree three times:
measure all views
layout views
draw views
ViewGroups
ViewGroups are invisable that contain other Views , use it to group/organize Views and ViewGroups.
Predefined ViewGroups:
RadioGroup- contains a set of radio buttons
TimePicker -
DatePicker
WebView - a WebGroup that displays webpages
MapView
Gallery - displays a set of data that is horizontally scrollable, data is managed by an adapter
Spinner - a scrollable list of items, user can select one. Items are managed by a ListAdapter
Layouts are ViewGroups.
LinearLayout - less or more fixed order
RelativeLayout - layout is relative
TableLayout - child views are arranged in rows and columns
GridView - 2-dimensional scrollable View
Menus and ActionBar
Activities support Menus (a quick way to access important functions).
Activities can add items to the menu.
Menu types:
options menu (when the user presses the Menu key, old stuff), global for the whole application
context menu (view specific menu shown when user presses and holds the view)
Creating menus
getMenuInflater() , and inflate with a context menu
ActionBar, similar to desktop applications, quick access to common operations .
Multiple Activities and Fragments can add items there.
2 types of notifications, "Toast" messages, and Notifications at the status bar / drawer.
The second allowes for custom Notifications, with custom views, custom sounds, Autocancel or not, and the possibility for a "PendingIntent" that gets fired when the user clicks on the notification at the drawer. (See last part of the video, or the project NotificationStatusBarWithCustomView.
BroadcastReceiver
Base class for components that :
wait for and receive events
process and react to these events
BroadcastReceiver register the events (Intents) they are interested in.
When an intent is being broadcast, the BroadcastReceiver gets it via it's onReceive() method.
Typical use case:
register BroadcastReceivers
Broadcast an Intent
Android delivers the Intent to registered recipients
BroadcastReceivers get (onReceive() ) and handle the Intent
Registering can be
statically via AndroidManifest.xml ( <receiver> and <intent-filter> elements ) => android:name specifies the classname of the receiver, android:permission declares the permission that is required for a sender application to broadcast this intent.
dynamically with code (registerReceive()), can be in 2 scopes: LocalBroadcastManager (this application) or Context (any application)
When sending a Broadcast Intent, you can specify a permission that Receivers should have in order to get the Intent .
Event Broadcast:
Normal - processing order undefined
Ordered - sequential processing in priority order ( sendOrderedBroadcasts())
And:
Sticky - Event is stored after initial broadcast, so Receivers can get it when they startup after the Intent was broadcast (for example for system state changes like battery level)
Non-Sticky - Event is discarded after initial broadcast
Debugging tips
have Android log extra information during the intent processing (Intent.setFlag(FLAG_DEBUG_LOG_RESOLUTION))
list dynamically registered BroadcastReceivers : adb shell dumpsys activity xx
list statically registered BroadcastReceivers : adb shell dumpsys package
When an intent is delivered to the onReceive(), two parms are passed:
the context in which the receiver is running
the intent
The process receiving the intent has high priority during onReceive() processing and runs on the main thread, so make it quick. If you have long running work, let it handle by a Service.
Receiver is not considered valid after onReceive() returns. Android might terminate the BroadcastReceiver .
BroadcastReceivers can't wait for asynchronous callbacks, because they then migth already be gone. So no ShowDialogs and not startActivityForResult().
BroadcastReceivers can abort the broadcast, making the Intent unavailable to receivers lower in the prio. (abortBroadcast())
BroadcastReceivers can setResultData() to the broadcast, so each receiver can see what the previous receiver has done with the result.
With sticky intents, intents can "overwrite" older intents they match.
When a BroadcastReceiver registers itself, all Android cached sticky intents will be delivered to the broadcastreceiver, and one matching sticky intent is returned to the caller.
Threads, AsyncTasks and Handlers
Only the Thread that originally created a view hierarchy is allowed to touch these views !.
So, using the UI Toolkit is reserved for the UI thread.
Android provides several methods that are guaranteed to run on the UI thread:
boolean View.post(Runnable action)
void Activity.rubOnUIThread(Runnable action)
AsyncTask
Provides a structured way to manage work involving background and UI threads.
General approach:
Background thread:
performs work
indicates progress
UI Thread:
does setup
publishes intermediate progress
uses results
AsyncTask is a generic class, it takes 3 parameters:
AsyncTask<Params,Progress, Result>
params - type used in background work
progress - type used when indicating progress
result - type of result
AsyncTask runs as follows:
void onPreExecute() (UI Thread)
Result doInBackground(Params...) (background thread)
this method may call publishProgress(Progress...)
this call will result in an invoke of onProgressUpdate(Progress...) on the UI Thread
void onPostExecute(Result) (UI Thread)
Handler
Is associated with a specific Thread. One Thread can hand off work to another Thread by sending Messages and posting Runnables to a Handler associated with another ThreadM
A Handler can handle both. A Runnable is an executable piece of code, so the sender of the Runnable knows what to run and delegates this to the handler to run on his thread.
A Message can also be sent, but in that case the code to be executed is in the Handler class, it should determine from the Message what/how to run stuff. (the implementation is in the Handler)
Each Android Thread is associated with a MessageQueue that holds Runnables and Messages. With this MessageQueue there is a looper associated, which picks off the runnables and messages of the queue.
So :
create Runnable object
use handler.post(Runnable) to submit it to the handler
the Runnable is placed on the MessageQueue
same with Message...
use handler.sendMessage(Message) to pass it on the the MessageQueue
meanwhile the looper sits and waits on things in the MessageQueue
if a Message arrives, the looper calls the handler.handleMessage()
if a Runnable arrives, the looper will call the Runnable's run() method
Alternatives handler method's :
postAtTime(Runnable, long)
postDelayed(Runnable, long)
create Message with either handler.obtainMessage() or Message.obtain()
sendMessageAtFrontOfQueue()
sendMessageAtTime()
sendMessageDelayed()
Alarms
Mechanism to send Intents at some point in the future.
An app can have code executed, even when the app itself is no longer running.
Even if the device is asleep.
The Alarm can wake up the device, or the Alarm can go off when the device wakes up.
Alarms are cancelled on device shutdown/restart.
Examples:
MMS uses alarms to retry sending messages
Settings, timeout the bluetooth findability
Interact with the AlarmManager: getSystemService(Context.ALARM_SERVICE)
Set the alarm with set(int type, long triggerTime, PendingIntent intent) and setRepeating(. . . ) and setInexactRepeating(. . . ) , the last one lets Android decide handle it, for more efficient battery use.
Alarm types, 2 degrees of configurability:
how to interpret time , real/walclock time since epoch, relative to system uptime
what todo is device sleeps when alarm goes off, wakeup now and deliver intent , or let the device asleep and deliver when it wakes up
Canvas is suitable if you want to update the drawing frequently.
Access to Canvas through GenericViews (less frequent updates) or a subclass of SurfaceView (for frequent updates)
provide secondary thread for drawing.
ostInvalidate() tells android to redraw a View.
For higher frequency smoothly updates, use Canvas with SurfaceView. SurfaceView need a separate thread.
SurfaceView must be subclassed and this subclass must implement the SurfaceHolder.callBack() interface.
set up a SurfaceView
getHolder() method to acquire its SurfaceHolder
register the SV by calling the addCallback() ==> surfaceCreated() is called in return
create a Thread used for executing drawing operations
draw to the SurfaceView
SurfaceHolder.lockCanvas()
Canvas.drawBitmap()
SurfaceHolder.unlockCanvasAndPost()
Animation
Android supports several Animation support classes.
TransitionDrawable
AnimationDrawable
Animation
.. not many notes on this subject , no time and interest this time....
MultiMedia
Important MultiMedia classes:
AudioManager & SoundPool
RingtoneManager & RingTone
MediaPlayer & MediaRecorder
Camera
AudioManager
manages volume, system sound, effects and ringer mode control
acquire AudioManager instance via Context.getSystemService(Context.AUDIO_SERVICE)
then Load and Play sound Effects, manage the volume, manage Peripherals
SoundPool represents a collection of audio, multiple sample at the same time
RingToneManager provides access to audio clips used for incoming phone calls, notifications, alarms etc.
It allows application to get and set ringtones and to stop/play them.
MediaPlayer controls the playback of audio and video streams and files.
common methods
setDataSource() - which streams to play
prepare() - initializes the player and loads the streams (it is synchronous, there is also an asynchronous version)
start()
pause()
seekTo()
stop()
release()
VideoView is a subclass of SurfaceView. Used for displaying video.
MediaRecorder used to record audio and video (state machine). Use setAudioSource() , setVideoSource(), and the other usual ones.
Camera - access the camera service. Your application can capture images, start/stop preview. You need CAMERA permissions of course. Also specify the uses-feature tag in AndroidManifest.xml.
Commona approach:
get camera instance
set camera parameters
setup and start the preview display (so the user can see what the camera sees)
Sensors are hardware devices that measure the physical environment.
There are 3 type of sensors:
Motion (speed and acceleration)
Position (magnetic compass)
Environment (pressure, ambient light)
Important classes:
SensorManager (getSystemService(Context.SENSOR_SERVICE)), to access a specific sensor : SensorManager.getDefaultSensor(int type) :
Sensor.TYPE_ACCELEROMETER
Sensor.TYPE_MAGNETIC_FIELD
Sensor.TYPE_PRESSURE
SensorEventListener interface must be implemented to get callbacks when there are new sensor readings or when a sensor's accuracy changes. (onAccuracyChanged(Sensor sensor, int accuracy) or onSensorChanged(SensorEvent event) ) also make sure to call un/registerSensor()
For registration you also pass in the rate at which you want your callbacks.
For unregistration you pass in the listener and a bitmask that specifies the Sensors to release.
SensorEvent
data is sensor-specific
sensor type
timestamp
accuracy
measurement data
Sensor Coordinate System
This does not change if the orientation changes.
X - right to left
Y - top to bottom
Z - down to up
Sensor values will vary constantly, for example, you cannot hold your device exactly straight or steady.
So these values can be filtered, in multiple ways:
Low-pass filter
deemphasize small transient force changes
emphasize long term constant forces
for example : een waterpas
high -pass filter
should ignore long term changes
emphasize short term changes
for example : a percussion instrument
Location & maps
Classes :
Location
represent position on the earth
has : latitude, longitude, timestamp
optionally : accuracy, altitude, speed, bearing
LocationProvider
represents a location data source, actual data may come from Satellites, Cell phone towers, Wifi APs
LocationProvider types:
network (wifi and cell tower) ==> permission ACCESS_COARSE_LOCATION
SharedPreferences
Small amounts of primitive data.
A persistent map, key-values, are persisted across application sessions.
Activity.getPreferences(mode) (mode=private) for one activity. Context.getSharedPreferences(name, mode) for data shared across multiple activities.
SharedPreferences.edit() returns a SharedPreferences.Editor object, and then things like putInt() putString() and remove(key), and finally Editor.commit().
retrieving sharedprefs:
getAll()
getString()
getBoolean()
PreferenceFragment
To display and modify User Preferences.
File Storage
Internal Storage
Small to medium amounts of private data, private to the applications.
File API
FileOutputStream.openFileOutput(String name, int mode) opens private file for writing, creates it if it does not exist.
External Storage
Larger amounts of data that is non-private, such as media files.
Media can appear and disappear without warning. So first determine the state of the storage, with Environment.getExternalStorageState().
MEDIA_MOUNTED - read/write access
MEDIA_MOUNTED_READ_ONLY
MEDIA_REMOVED
Requires permission: WRITE_EXTERNAL_STORAGE
Cache files
removed when storage is low
removed when app is uninstalled
Context.getCacheDir() returns absolute path to directory for temporary files.
Context.getExternalCacheDir()
Databases
Small to medium amounts of structured private data.
SQLite is full fledged, implements most of SQL92 and supports ACID transactions (Atomic, Consistent, Isolated, Durable).
Create subclass SQLiteOpenHelper. Call super() from subclass constructor to init the db.
override the onCreate() and onUpgrade()
use open and return methods
Database are stored in /data/data/<packagename>/databases directory
Content Providers
Centralized repository of structured data to be shared by multiple applications
ContentResolver class provides a db-style interface to the content provider (query , insert ,delete, update), also supports listeners (for updated information for example)
Context.getContentResolver() gets ref to ContentResolver.
Example ContentProviders :
Browser - bookmarks, history
call log - telephone usage
contacts - contact data
media - media database
userdictionary - database for predictive spelling
Data is represented as a database table.
Application identify the data they want with a URI :
content://authority/path/id
content is fixed for content providers
authority - id for the content provider
path - 0 or more segments indicating the type of data
id - a specific record (key)
CursorLoader
for intensive tasks loading data, it uses an AsyncTask. using the Loader.initLoader() passing in the Loader Callbacks.
Creating a ContentProvider
implement a storage subsystem (SQLite for example)
define a contract class to support users of your contentprovider
implement a ContentProvider subclass
declare and config it in the AndroidManifest.xml (provider tag)
Services
Services do not interact with users, so no user interface.
perform background processing , even if application terminates
allow code in one process to interact with code in another process
Context.startService(Intent)
Android can kill a service if it needs it's resources.
Services run in the main thread of the hosting application.
Binding to a service with Context.bindService(Intent, ServiceConnection, flags) .
A component can send requests to and receive response from a service.
A service will keep running as long as at least one component is connected.
Messenger class manages a handler. It allows message to be sent from one component to another. So use it for sequential processing.
The receiving component needs a Handler to process the messages, and creates a Messenger that provides a binder to a client that binds to the service??
The client binds to a service and receives a Binder object, this binder object is used to create a Messenger, which knows how to send messages to the Handler that was set up by the service .
The client then uses the Messenger to send messages to the Handler in the service.
If you need services that are accessed in parallel , you need AIDL (Android Interface Definition Language)
define remote interface
implement remote service
implement service methods
implement client methods
Create a .aidl file. Defines how components can interface with your service. It is similar to Java interfaces.
AIDL types :
Java primitives
String
CharSequence
other AIDL-generated interfaces
classes implementing the Parcelable interface
List with the above
Map with the above
> Generic maps not supported
Services must implement a inner class called <class>.Stub.
coursera-android#
Table of Contents
Time spent#
TODO#
Weeks#
Week 1#
metskem@athena ~ $ telnet localhost 5554 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Android Console: type 'help' for a list of commands OK help Android console command help: help|h|? print a list of commands event simulate hardware events geo Geo-location commands gsm GSM related commands cdma CDMA related commands kill kill the emulator instance network manage network settings power power related commands quit|exit quit control session redir manage port redirections sms SMS related commands avd control virtual device execution window manage emulator window qemu QEMU-specific commands sensor manage emulator sensors try 'help <command>' for command-specific help OKweek 2#
Four main building blocks in Android :
Non code (resource) files
Activity
The Activity Lifecycle:
-- onRestart() , do specific stuff required after activity was stopped
-- onStart() , loading persistent application state
-- onResume() , start foreground-only actions
-- onPause() , shutdown foreground-only actions, save persistent stat
-- onStop() , cache state (may not be called when Android kills the activity)
-- onDestroy() , release activity resources (may not be called when Android kills the activity)
Activities are created by creating Intents, and passing these Intents to startActivity() or startActivityForResult() . Started activity can set the result with Activity.setResult().
AndroidManifest.xml
Contains:
week 3#
Intents
Intent is a data structure that represents:
Intent fields:
Activity is a subclass of Context, so you can for example use new Intent(MyActivity.this, SecondActivity.class);
Two ways of Intent resolution:
Implicit Intent resolution uses the following data of the Intent:
Installed apps have intent-filters defined in their AndroidManifest.xml.
These filters can specify things like data, action, category and so on. If they want to react to implicit intents, they always have to specify the intent-filter category.DEFAULT.
If you want to know what's on your device (for example all intent filters) :
Permissions
Android uses permissions to protect Resources, data and operations.
Applications can define their own permissions to protect their own resources (other apps are required to have those permissions). (permission tag) And applications can define the permissions they use themselves (uses-permission).
There are application-level permissions and component-level permissions, the latter take precedence.
And we have :
Fragments
Introduced in Android 3.0 to better support larger screens (Tablets).
Fragments represent a portion of a UI within an Activity => multi-pane activities.
A single Fragment can be used across multiple activities.
The lifecycle of a Fragment is coordinated with the lifecycle of an Activity, but they also have their own lifecycle callbacks.
Fragment lifecycle states :
Fragment callbacks :
Statically add Fragment to Activity by specifying them in the layout file, or programmatically using the FragmentManager.
week 4#
User Interfaces
The View is the place and the means to exchange information between the user and the Application.
View is the key building block. It occupies a rectangular space on the screen, they are responsible for drawing themselves and handling events.
Predefined Views:
Common View operations:
View Listener Interfaces:
Displaying Views
Views are organized as a tree, Views with child Views Android walks the View tree three times:
ViewGroups
ViewGroups are invisable that contain other Views , use it to group/organize Views and ViewGroups.
Predefined ViewGroups:
Layouts are ViewGroups.
LinearLayout - less or more fixed order RelativeLayout - layout is relative TableLayout - child views are arranged in rows and columns GridView - 2-dimensional scrollable View
Menus and ActionBar
Activities support Menus (a quick way to access important functions). Activities can add items to the menu.
Menu types:
Creating menus getMenuInflater() , and inflate with a context menu
ActionBar, similar to desktop applications, quick access to common operations . Multiple Activities and Fragments can add items there.
Dialogs:
week 5#
Notifications
2 types of notifications, "Toast" messages, and Notifications at the status bar / drawer.
The second allowes for custom Notifications, with custom views, custom sounds, Autocancel or not, and the possibility for a "PendingIntent" that gets fired when the user clicks on the notification at the drawer. (See last part of the video, or the project NotificationStatusBarWithCustomView.
BroadcastReceiver
Base class for components that :
BroadcastReceiver register the events (Intents) they are interested in. When an intent is being broadcast, the BroadcastReceiver gets it via it's onReceive() method.
Typical use case:
Registering can be
When sending a Broadcast Intent, you can specify a permission that Receivers should have in order to get the Intent .
Event Broadcast:
And:
Debugging tips
When an intent is delivered to the onReceive(), two parms are passed:
The process receiving the intent has high priority during onReceive() processing and runs on the main thread, so make it quick. If you have long running work, let it handle by a Service.
Receiver is not considered valid after onReceive() returns. Android might terminate the BroadcastReceiver . BroadcastReceivers can't wait for asynchronous callbacks, because they then migth already be gone. So no ShowDialogs and not startActivityForResult().
BroadcastReceivers can abort the broadcast, making the Intent unavailable to receivers lower in the prio. (abortBroadcast())
BroadcastReceivers can setResultData() to the broadcast, so each receiver can see what the previous receiver has done with the result.
With sticky intents, intents can "overwrite" older intents they match.
When a BroadcastReceiver registers itself, all Android cached sticky intents will be delivered to the broadcastreceiver, and one matching sticky intent is returned to the caller.
Threads, AsyncTasks and Handlers
Only the Thread that originally created a view hierarchy is allowed to touch these views !.
So, using the UI Toolkit is reserved for the UI thread. Android provides several methods that are guaranteed to run on the UI thread:
AsyncTask
Provides a structured way to manage work involving background and UI threads.
General approach:
AsyncTask is a generic class, it takes 3 parameters: AsyncTask<Params,Progress, Result>
AsyncTask runs as follows:
Handler
Is associated with a specific Thread. One Thread can hand off work to another Thread by sending Messages and posting Runnables to a Handler associated with another ThreadM
A Handler can handle both. A Runnable is an executable piece of code, so the sender of the Runnable knows what to run and delegates this to the handler to run on his thread. A Message can also be sent, but in that case the code to be executed is in the Handler class, it should determine from the Message what/how to run stuff. (the implementation is in the Handler)
Each Android Thread is associated with a MessageQueue that holds Runnables and Messages. With this MessageQueue there is a looper associated, which picks off the runnables and messages of the queue.
So :
Alternatives handler method's :
Alarms
Mechanism to send Intents at some point in the future. An app can have code executed, even when the app itself is no longer running. Even if the device is asleep. The Alarm can wake up the device, or the Alarm can go off when the device wakes up. Alarms are cancelled on device shutdown/restart.
Examples:
Interact with the AlarmManager: getSystemService(Context.ALARM_SERVICE)
Set the alarm with set(int type, long triggerTime, PendingIntent intent) and setRepeating(. . . ) and setInexactRepeating(. . . ) , the last one lets Android decide handle it, for more efficient battery use.
Alarm types, 2 degrees of configurability:
RTC_WAKEUP, RTC, ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP/
3 ways to get the PendingIntent : getActivity() , getBroadcast(), getService()
Networking
Useful classes:
AndroidHttpClient is an Android implementation of the Apache HttpClient, with extra customization options.
AndroidHttpClient offers use of separate response handler classes, like the JSONResponseHandler
week 6#
Graphics
Classes:
Drawing to Views, attach Drawables to Views (via xml or programming)
ShapeDrawable Are use for simple shapes, represented by subclasses:
Canvas
You need 4 things:
Drawing primitives:
Paint: setStrokeWidth(), setTextSize(), setColor(), setAntiAlias()
Canvas is suitable if you want to update the drawing frequently. Access to Canvas through GenericViews (less frequent updates) or a subclass of SurfaceView (for frequent updates)
provide secondary thread for drawing.
ostInvalidate() tells android to redraw a View.
For higher frequency smoothly updates, use Canvas with SurfaceView. SurfaceView need a separate thread.
SurfaceView must be subclassed and this subclass must implement the SurfaceHolder.callBack() interface.
Animation
Android supports several Animation support classes.
- TransitionDrawable
- AnimationDrawable
- Animation
.. not many notes on this subject , no time and interest this time....MultiMedia
Important MultiMedia classes:
AudioManager
SoundPool represents a collection of audio, multiple sample at the same time
RingToneManager provides access to audio clips used for incoming phone calls, notifications, alarms etc. It allows application to get and set ringtones and to stop/play them.
MediaPlayer controls the playback of audio and video streams and files.
common methods
VideoView is a subclass of SurfaceView. Used for displaying video.
MediaRecorder used to record audio and video (state machine). Use setAudioSource() , setVideoSource(), and the other usual ones.
Camera - access the camera service. Your application can capture images, start/stop preview. You need CAMERA permissions of course. Also specify the uses-feature tag in AndroidManifest.xml.
Commona approach:
week 7#
Sensors
Sensors are hardware devices that measure the physical environment. There are 3 type of sensors:
Important classes:
- SensorManager (getSystemService(Context.SENSOR_SERVICE)), to access a specific sensor : SensorManager.getDefaultSensor(int type) :
- Sensor.TYPE_ACCELEROMETER
- Sensor.TYPE_MAGNETIC_FIELD
- Sensor.TYPE_PRESSURE
- SensorEventListener interface must be implemented to get callbacks when there are new sensor readings or when a sensor's accuracy changes. (onAccuracyChanged(Sensor sensor, int accuracy) or onSensorChanged(SensorEvent event) ) also make sure to call un/registerSensor()
For registration you also pass in the rate at which you want your callbacks.
For unregistration you pass in the listener and a bitmask that specifies the Sensors to release.
- SensorEvent
- data is sensor-specific
- sensor type
- timestamp
- accuracy
- measurement data
Sensor Coordinate System This does not change if the orientation changes.Sensor values will vary constantly, for example, you cannot hold your device exactly straight or steady. So these values can be filtered, in multiple ways:
Location & maps
Classes :
Different Tradeoffs for each provider between:
LocationManager options:
Procedure for getting location:
MAPS
A visual presentation of area. Android provides maps support through the Google Maps Android V2 API
Map types:
Customizing the map:
Some map classes:
Setting up Maps application:
Required permissions:
week 8#
Data management
SharedPreferences
Small amounts of primitive data.
A persistent map, key-values, are persisted across application sessions.
Activity.getPreferences(mode) (mode=private) for one activity.
Context.getSharedPreferences(name, mode) for data shared across multiple activities.
SharedPreferences.edit() returns a SharedPreferences.Editor object, and then things like putInt() putString() and remove(key), and finally Editor.commit().
retrieving sharedprefs:
PreferenceFragment
To display and modify User Preferences.
File Storage
Internal Storage
Small to medium amounts of private data, private to the applications.
File API
FileOutputStream.openFileOutput(String name, int mode) opens private file for writing, creates it if it does not exist.
External Storage
Larger amounts of data that is non-private, such as media files. Media can appear and disappear without warning. So first determine the state of the storage, with Environment.getExternalStorageState().
Requires permission: WRITE_EXTERNAL_STORAGE
Cache files
Context.getCacheDir() returns absolute path to directory for temporary files.
Context.getExternalCacheDir()
Databases
Small to medium amounts of structured private data. SQLite is full fledged, implements most of SQL92 and supports ACID transactions (Atomic, Consistent, Isolated, Durable).
Database are stored in /data/data/<packagename>/databases directory
Content Providers
Centralized repository of structured data to be shared by multiple applications
ContentResolver class provides a db-style interface to the content provider (query , insert ,delete, update), also supports listeners (for updated information for example)
Context.getContentResolver() gets ref to ContentResolver. Example ContentProviders :
Data is represented as a database table. Application identify the data they want with a URI :
content://authority/path/id
CursorLoader
for intensive tasks loading data, it uses an AsyncTask. using the Loader.initLoader() passing in the Loader Callbacks.
Creating a ContentProvider
Services
Services do not interact with users, so no user interface.
Context.startService(Intent)
Android can kill a service if it needs it's resources. Services run in the main thread of the hosting application.
Binding to a service with Context.bindService(Intent, ServiceConnection, flags) .
A component can send requests to and receive response from a service.
A service will keep running as long as at least one component is connected.
Messenger class manages a handler. It allows message to be sent from one component to another. So use it for sequential processing.
The receiving component needs a Handler to process the messages, and creates a Messenger that provides a binder to a client that binds to the service??
The client binds to a service and receives a Binder object, this binder object is used to create a Messenger, which knows how to send messages to the Handler that was set up by the service . The client then uses the Messenger to send messages to the Handler in the service.
If you need services that are accessed in parallel , you need AIDL (Android Interface Definition Language)
Create a .aidl file. Defines how components can interface with your service. It is similar to Java interfaces.
AIDL types :
Services must implement a inner class called <class>.Stub.