This page (revision-58) was last changed on 23-Apr-2022 17:06 by HarryMetske

This page was created on 23-Apr-2022 17:05 by Harry Metske

Only authorized users are allowed to rename pages.

Only authorized users are allowed to delete pages.

Page revision history

Version Date Modified Size Author Changes ... Change note
58 23-Apr-2022 17:06 29 KB HarryMetske to previous
57 23-Apr-2022 17:05 29 KB HarryMetske to previous | to last
56 23-Apr-2022 17:05 28 KB HarryMetske to previous | to last
55 23-Apr-2022 17:05 26 KB Harry Metske to previous | to last
54 23-Apr-2022 17:05 26 KB Harry Metske to previous | to last
53 23-Apr-2022 17:05 24 KB Harry Metske to previous | to last
52 23-Apr-2022 17:05 24 KB 10.0.0.138 to previous | to last
51 23-Apr-2022 17:05 23 KB 10.0.0.138 to previous | to last
50 23-Apr-2022 17:05 23 KB 10.0.0.138 to previous | to last
49 23-Apr-2022 17:05 22 KB 10.0.0.138 to previous | to last
48 23-Apr-2022 17:05 22 KB 10.0.0.138 to previous | to last
47 23-Apr-2022 17:05 22 KB 10.0.0.138 to previous | to last
46 23-Apr-2022 17:05 20 KB 10.0.0.138 to previous | to last
45 23-Apr-2022 17:05 20 KB 10.0.0.138 to previous | to last
44 23-Apr-2022 17:05 20 KB HarryMetske to previous | to last
43 23-Apr-2022 17:05 19 KB HarryMetske to previous | to last
42 23-Apr-2022 17:05 19 KB Harry Metske to previous | to last
41 23-Apr-2022 17:05 19 KB Harry Metske to previous | to last

Page References

Incoming links Outgoing links

Version management

Difference between version and

At line 16 added 11 lines
|2014-02-12 | 1
|2014-02-14 | 1
|2014-02-15 | 2
|2014-02-18 | 1
|2014-02-19 | 2
|2014-02-20 | 1
|2014-02-21 | 1
|2014-02-25 | 1
|2014-02-26 | 1
|2014-03-01 | 1
|2014-03-02 | 2
At line 288 added 2 lines
ActionBar, similar to desktop applications, quick access to common operations .
Multiple Activities and Fragments can add items there.
At line 291 added 5 lines
Dialogs:
* AlertDialog
* ProgressDialog
* DatePickerDialog
* TimePickerDialog
At line 297 added 541 lines
! 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 :
* 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
RTC_WAKEUP, RTC, ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP/
3 ways to get the PendingIntent : ''getActivity() , getBroadcast(), getService()''
__Networking__
Useful classes:
* java.net.Socket / URL
* org.apache.HttpRequest / HttpResponse
* android.net.URI / AndroidHttpClient / AudioStream
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:
* Drawable (bitmap, color, shape)
** ShapeDrawable
** BitmapDrawable
** ColorDrawable
Drawing to Views, attach Drawables to Views (via xml or programming)
__ShapeDrawable__
Are use for simple shapes, represented by subclasses:
* PathShape (lines)
* RectShape (rectangles)
* OvalShape (ovals & rings)
__Canvas__
You need 4 things:
* bitmap
* canvas (for drawing to the underlying bitmap
* drawing primitive (rect, path, text, bitmap)
* paint object (for setting drawing colors & styes)
Drawing primitives:
* drawText()
* drawPoints()
* drawColors()
* drawOval()
* drawBitmap()
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.
* 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)
* take a picture & process image data
* release the camera
! week 7
__Sensors__
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
*** GPS - satellite ==> permission ACCESS_FINE_LOCATION
*** passive - piggyback on the readings requested by other applications ==> permission ACCESS_FINE_LOCATION
Different __Tradeoffs__ for each provider between:
* cost
* accuracy
* availability
* timeliness
* GPS - expensive, accurate, slower, available outdoors
* Network - cheaper, less accurate, faster, but wifi or cell phone tower required
* passive - cheapest, fastest, not always available
LocationManager options:
* determine last know location
* register for location updates (LocationListener interface)
* register to receive intents when device nears or moves away from given geographic area
Procedure for getting location:
* start listening for location updates
* maintain a "current best estimate" of location
* determine when good enough, en then unregister the listener
* use best estimate
__MAPS__
A visual presentation of area.
Android provides maps support through the Google Maps Android V2 API
Map types:
* normal maps (tradition road map)
* satellite maps (aerial photograph)
* hybrid maps (both combined)
* terrain maps (topographic details)
Customizing the map:
* change the camera position (zoom)
* add markers and ground overlays
* respond to gestures (pinch and zoom)
* indicate current location
Some map classes:
* GoogleMap
* MapFragment
* Camera
* Marker
Setting up Maps application:
* set up the google play services SDK
* obtain an API key
* specify settings in AndroidManifest.xml
* add map to project
Required permissions:
* INTERNET (to get the maps from google)
* ACCESS_NETWORK_STATE (to determine if maps can be downloaded)
* WRITE_EXTERNAL_STORAGE (to save map data)
* com.google.android.providers.gsf.permission.READ_GSERVICES
* one or more LOCATION perms
! 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:
* 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.