android session-5-sajib
DESCRIPTION
TRANSCRIPT
Android Training
Session - 5
Presented By: A.T.M. Hassan Uzzaman
Agendas
• Threads & Asyntask• Using SDcards – Reading and writing• XML Parsing• JSON Parsing• Android Phone Status• Network connectivity services
Threads / Concurrency Android modifies the user interface and handles input events from
one single user interface thread. This thread is also called the main thread.
If you perform a long lasting operation, for example accessing data from the Internet, the application blocks until the corresponding operation has finished.
Android will show an “Application Not Responding ( ANR )” error if a View does not return from handling an event within 5 seconds
Or, if some code running in the “main thread” prohibits UI events from being handled
This means that any long-running code should run in a background thread
However, background threads are not allowed to modify UI elements!
Using Java threads in Android
Using Java threading in Android
Android supports the usage of the Thread class to perform asynchronous processing.
Android also supplies the java.util.concurrent package to perform something in the background, e.g. using the ThreadPools and Executor classes.
Disadvantages of using Java threads in Android
We have to handle the following requirements in code: Synchronization with the main thread if post back results
to the user interface No default for canceling the thread No default thread pooling No default for handling configuration changes in Android
Concurrency constructs in AndroidHandler
The Handler class can be used to register to a thread and provides a simple channel to send data to this thread.
if we create a new instance of the Handler class in the onCreate() method of our activity, the resulting Handler object can be used to post data to the main thread.
The data which can be posted via the Handler class can be an instance of the Message or the Runnable class.
A Handler is particular useful if we have want to post multiple times data to the main thread.
Creating and reusing instances of Handlers To use a handler we have to subclass it and override the
handleMessage() method to process messages. Our thread can post messages via
the sendMessage(Message) method. To process a Runnable we can use
the post() method.// Reuse existing handler if we don'thandler = getWindow().getDecorView().getHandler();
Sample Application - Handler
Concurrency constructs in AndroidAsyncTask
Create a class that extends AsyncTask To start the new thread, call the AsyncTask's execute method When execute is called, Android does the following:
runs onPreExecute in the main (UI) thread runs doInBackground in a background thread runs onPostExecute in the main (UI) thread
TypeOfVarArgParams is passed into the doInBackground() method as input, ProgressValue is used for progress information and ResultValue must be returned from doInBackground() method and is passed to onPostExecute() as a parameter.
The doInBackground() method contains the coding instruction which should be performed in a background thread. This method runs automatically in a separate Thread.
The onPostExecute() method synchronizes itself again with the user interface thread and allows it to be updated. This method is called by the framework once the doInBackground() method finishes.
Sample Application - AsyncTask
Handlers Vs AsyncTask Handlers
are used as a way of passing messages between threads. In this case, the UI thread has a handler, which was sent as a
parameter when server-thread was created. Every time it needs to update UI, it posts a message to the UI
thread, which periodically checks for new messages and executes
Runnables attached to them. AsyncTask
is a convenience class for doing some work on a new thread and use the results on the thread from which it got called (usually the UI thread) when finished.
enables proper and easy use of the UI thread. This class allows to perform background operations and publish
results on the UI thread without having to manipulate threads and/or handlers.
An asynchronous task is defined by 3 generic types, called Params, Progress and Result,
And 4 steps, called onPreExecute doInBackground onProgressUpdate onPostExecute
Using SD cards – Reading and writing
The classes for XML parsing in Android
DOMBuilder: The DOM parser can be used which creates a complete
memory model of the XML and can be used to either create or parse XML.
DOM parsers generally consume a lot of memory.
SAXParsers: The SAXParsers can also be used to parse XML and
consume much lesser memory then DOM parsers. The SAXParsers can be used only to parse XMLs not to
create them.
XMLPullParser: Android recommends the use of the XMLPullParser. Android gives a multiple implementation of the
XMLPullParser and we can use any of them in our program.
XMLPullParser
XmlPullParserFactory pullParserFactory;try {
pullParserFactory = XmlPullParserFactory.newInstance();XmlPullParser parser = pullParserFactory.newPullParser();
} catch (XmlPullParserException e) {e.printStackTrace();
}
Sample Application -
XMLPullParser
DOMBuilder
DocumentBuilderFactory DOMfactory;try{
DOMfactory = DocumentBuilderFactory.newInstance();DocumentBuilder DOMbuilder = DOMfactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {e.printStackTrace();
}
SAX Parsers
SAXParserFactory SAXfactory;try {
SAXfactory = SAXParserFactory.newInstance();SAXParser SAXParserObj = SAXfactory.newSAXParser();
} catch (Exception e) {e.printStackTrace();
}
XML Writer
XmlSerializer serializer = Xml.newSerializer();StringWriter writer = new StringWriter();try {
serializer.setOutput(writer);serializer.startDocument("UTF-8", true);serializer.startTag("", "people");serializer.attribute("", "number", "1");serializer.endTag("", "people");serializer.endDocument();
} catch (Exception e) {throw new RuntimeException(e);
}System.out.println(writer.toString());
Sample Application - XML Writer
JSONObject Vs JsonReader JSONObject –
Class has been in Android since the very beginning (API level 1) Easy to use and probably the developer's default choice for their
JSON parsing needs.
The JSONObject class is like DOM; it reads the whole object into memory.
On mobile devices with limited resources that's not always the best idea.
JsonReader – (Google decided to provide an alternative) Presents data for parsing with a stream, similar to
SAXparsers.
This class, is only available in API level 11 and up (Honeycomb and Ice Cream Sandwich).
Might not help if we want to target Froyo and Gingerbread devices.
Google has made this class available in an open source library: google-gson.
Sample Application - JSONObject
Sample Application - JsonReader
Accessing Phone services Service Provider Related
Service state Cell Location Call State Connection State Signal Strength Data Exchange
Phone Specific Device ID Phone number SW Version Operator Name SIM Country Code SIM Operator SIM Serial No Subscriber ID Network type Phone type Battery Related Information.
Permissions in Android manifestNo Information Permission
1 Cell location ACCESS_COARSE_LOCATIONACCESS_FINE_LOCATION
2 Call State CHANGE_NETWORK_STATE
3 Data Connection State
4 Signal Strength
5 Data Direction States
6 Service State
7 Device ID READ_PHONE_STATE
8 Phone Number READ_PHONE_STATE
9 Operator Name READ_PHONE_STATE
10 SIM Operator READ_PHONE_STATE
11 SIM Country Code READ_PHONE_STATE
12 SIM Serial No. READ_PHONE_STATE
13 Subscriber ID READ_PHONE_STATE
14 Network Type ACCESS_NETWORK_STATE
15 Phone Type
Permissions in the AndroidManifest.xml file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_UPDATES"/>
The android.telephony.TelephonyManager
Any information related to the telephony services on the device has to be accessed via TelephonyManager class.
This class cannot be instantiated directly instead we retrieve a reference to an instance through
TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
The PhoneStateListener object The PhoneStateListener class is responsible for monitoring
changes in specific telephony states. We shall override the methods for the state that we wish to
receive updates for in the PhoneStateListener object. And pass the PhoneStateListener instance, along
with bitwise-or of the LISTEN_ flags to TelephonyManager.listen().
int events = PhoneStateListener.LISTEN_SIGNAL_STRENGTH | PhoneStateListener.LISTEN_DATA_ACTIVITY | PhoneStateListener.LISTEN_CELL_LOCATION | PhoneStateListener.LISTEN_CALL_STATE | PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE | PhoneStateListener.LISTEN_SERVICE_STATE;
tm.listen(phoneListener, events);
Listening to Phone States onCallStateChanged
TelephonyManager.CALL_STATE_IDLE: Device call state : No activity. TelephonyManager.CALL_STATE_RINGING: Device call state : A new call
arrived and is ringing or waiting. TelephonyManager.CALL_STATE_OFFHOOK: At least one call exists that is
dialing, active, or on hold, and no calls are ringing or waiting.
onDataConnectionStateChanged TelephonyManager.DATA_CONNECTED: Indicates IP traffic should be
available. TelephonyManager.DATA_CONNECTING: Currently setting up a data
connection. TelephonyManager.DATA_DISCONNECTED: Indicates IP Traffic is not
available. TelephonyManager.DATA_SUSPENDED: The connection is up, but IP traffic is temporarily unavailable. For example, in a 2G network, data activity may be suspended when a voice call arrives
Listening to Phone States onDataActivity
TelephonyManager.DATA_ACTIVITY_NONE: No IP Traffic. TelephonyManager.DATA_ACTIVITY_IN: Receiving IP Traffic TelephonyManager.DATA_ACTIVITY_OUT: Currently sending IP Traffic TelephonyManager.DATA_ACTIVITY_INOUT: Currently sending and
receiving IP Traffic TelephonyManager.DATA_ACTIVITY_DORMANT: Data connection is active,
but physical link is down
End Listening to Phone States
tm.listen(phoneListener, PhoneStateListener.LISTEN_NONE);
Sample Application - Phone States
Phone Battery The android.os.BatteryManager class provides information
related to the status of the phone battery in the form of strings and constants.
Also we can extract both the current charging status and, if the device is being charged, whether it's charging via USB or AC charger using.
BatteryManager.BATTERY_PLUGGED_AC - Battery is plugged to an AC source BatteryManager.BATTERY_PLUGGED_USB - Battery is plugged to a USB source
BatteryManager.BATTERY_STATUS_CHARGING - Battery is connected to a power supply and is charging
BatteryManager.BATTERY_STATUS_DISCHARGING - Battery is discharging BatteryManager.BATTERY_STATUS_FULL - Battery charge is complete
The BatteryManager The BatteryManager broadcasts all battery and charging details
in a sticky Intent that includes the charging status. By hooking in to these intents we can continuously monitor the
status of the phone battery. To achieve this, we register a BroadcastReceiver to be run in the
main activity thread (BatteryStatusActivity). The receiver will be called with any broadcast Intent that matches
filter (Intent.ACTION_BATTERY_CHANGED), in the main application thread.
Once registered, whenever the BroadcastReceiver is receiving an Intent broadcast (i.e. from BatteryManager), we shall update the status.
More information on best practices for Monitoring the state of battery can be found here .
Sample Application – Phone Battery States
Sample Application –NetworkActivity
References
developer.android.com
developer.android.com/reference/android/util/JsonReader.html
developer.android.com/reference/android/app/Service.html
developer.android.com/reference/android/telephony/TelephonyManager.html
developer.android.com/reference/android/os/BatteryManager.html
developer.android.com/training/monitoring-device-state/battery-monitoring.html
Questions ?
Thank You.