This document provides an overview of several Android development topics, including the Simple framework for serializing XML into Java objects, the Android process and thread model, AsyncTask for asynchronous operations, the Volley networking framework, and debugging using Eclipse. It describes the core components and best practices for each topic at a high level.
2. Agenda
1. Simple Framework to serialize xml into java object.
2. Android Process and Thread model.
3. AsyncTask- best practices.
4. Volley framework for networking.
5. Demo of Running debugger in eclipse.
3. Simple Framework
Simple is a high performance XML serialization and
configuration framework for Java. Its goal is to provide an
XML framework that enables rapid development of XML
configuration and communication systems. It offers full object
serialization and deserialization, maintaining each reference
encountered.
Serialize - The process of translating data structures or
object state into a format that can be stored.(eg. java object
to xml )
Deserialize – The opposite operation, extracting a data
structure from a series of bytes.(eg. Xml data to java object)
4. Simple Framework : Deserializing xml to java
object
The persister is given the class representing the serialized
object and the source of the XML document. To deserialize
the object the read method is used, which produces an
instance of the annotated object. Eg
Xml file -
<root id="123"><message>Example message</message></root>
Annotated class representing the serialized object
@Root(name="root")
public class Example {
5. Simple Framework : Deserialization cont...
@Element(name="message")
private String text;
@Attribute(name="id", required = false)
private int index;
public String getMessage() { return text; }
public int getId() { return index; }}
Deserializing the object -
Serializer serializer = new Persister();
File source = new File("example.xml");
Example example = serializer.read(Example.class, source);
6. Simple Framework : Basic Annotation-
Reading root element @Root, (name=”*”,required=true|
false)
Reading attributes @Attribute(name=”*”,required=true|
false)
Reading a list of elements @ElementList(inline=true)
Reading an array of elements @ElementArray
Reading an ElementMap eg. <element
key=”x”>abc</element> @ElementMap(entry="element",
key="key", attribute=true)
7. Simple Framework : Basic Annotation Cont...
Default object serialization @Default(DefaultType.FIELD|
DefaultType.PROPERTY)
Serializing with CDATA blocks @Element(Data=true)
Using XML namespaces
@Namespace(reference="http://test/test1", prefix="pre")
Other Libraries to serialize objects to XML and back again:
XStream and JIBX.
To know more visit:
http://simple.sourceforge.net/
8. Android Process and Thread Model
Process : A running instance of a program is called
Process.By default, all components of the same application
run in the same process.
Component of aplicationce can customize which process it
belongs to by giving android:process attribute in the
corresponding entry of manifenst file
Process lifecycle is maintained using importance hierarchy-
1. Foreground Process – activity having focus, services bound
to an activity, or services in onStart(), onDestroy(), onCreate()
or services start with startForeground() method.
9. Process Cont...
2.Visible Process - activity not foreground but still active usually
when onPause() is called
3.Services Process – services started with startService()
method as audio player.
4.Background Process - A process holding an activity that's not
currently visible to the user (the activity's onStop() method
has been called).
5.Empty Process - It doesn't hold any active application
components, used for caching purposes, to improve startup
time the next time a component needs to run in it.
10. Threads :
Thread is a basic unit of CPU utilization.
When an application is launched, the system creates a
thread of execution for the application, called "main” or UI-thread.
All components that run in the same process are instantiated
in the UI thread.
It is in charge of dispatching events to the appropriate user
interface widgets.
If everything is happening in the UI thread, performing long
operations such as network access or database queries will
block the whole UI.
11. Thread Cont...
When the thread is blocked, no events can be dispatched,
including drawing events. From the user's perspective, the
application appears to hang.
If the UI thread is blocked for more than a few seconds
(about 5 seconds currently) the user is presented with the
infamous "application not responding" (ANR) dialog. **BAD
USER EXPERIENCE**
Two rules to Android's single thread model:
1.Do not block the UI thread
2.Do not access the Android UI toolkit from outside the UI
thread.
12. Thread Cont...
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
//1. Do networking or Database task
//2. goback to UI thread for UI updation
//2.1 - Activity.runOnUiThread(Runnable)
//2.2 - View.post(Runnable)
//2.3 - View.postDelayed(Runnable, long)
//2.4 – Use Handler
}
}).start(); }
14. View.post Or VIew.postDelayed
demoImageView.post(new Runnable() {
public void run() {
demoImageView.setImageBitmap(bitmap);
}
});
View.onPostDelayed(Runnable r, long millisec)
call the runnable after the time specified.
16. Handler :
The Handler is the middleman between a new thread and the
message queue.
A Handler allows you to send and process Message and
Runnable objects associated with a thread's MessageQueue,
(Thread that create it).
Message : Defines a message containing a description and
arbitrary data object that can be sent to a Handler.(may
contain 2 int, 1 object)
MessageQueue : Low-level class holding the list of messages
to be dispatched by a Looper
17. Handler Cont...
There are two main uses for a Handler
(1) to schedule messages and runnables to be executed
as some point in the future
(2) to enqueue an action to be performed on a different
thread than your own.
Scheduling messages is accomplished with the
post(Runnable), postAtTime(Runnable, long),
postDelayed(Runnable, long), sendEmptyMessage(int),
sendMessage(Message),
sendMessageAtTime(Message, long), and
sendMessageDelayed(Message, long) methods.
18. Handler :
The post versions allow you to enqueue Runnable
objects to be called by the message queue when they
are received;
The sendMessage versions allow you to enqueue a
Message object containing a bundle of data that will be
processed by the Handler's handleMessage(Message)
method (requiring that you implement a subclass of
Handler).ons allow you to enqueue a Message object
containing a bundle of data that will be processed by the
Handler's handleMessage(Message) method (requiring
that you implement a subclass of Handler).
19. Handler : Using MessageQueue
final Handler myHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
updateUI((String)msg.obj);} };
(new Thread(new Runnable() {
@Override
public void run() {
Message msg = myHandler.obtainMessage();
msg.obj = doLongOperation();
myHandler.sendMessage(msg); }
})).start();
20. Handler : Using Runnable
final Handler myHandler = new Handler();
(new Thread(new Runnable() {
@Override
public void run() {
final String res = doLongOperation();
myHandler.post(new Runnable() {
@Override
public void run() {
updateUI(res);} });
})).start();
21. AsyncTask :
android.os.AsyncTask<Params, Progress, Result>
An asynchronous task is defined by a computation that runs
on a background thread and whose result is published on the
UI thread.
Helper class around Thread and Handler
The three generic types used by an asynchronous task are
the following:
1.Params - type of the parameters sent to the task upon execution.
2.Progress, the type of the progress units published during the background
computation.
3.Result, the type of the result of the background computation.
22. AsyncTask Cont...
AsyncTask must be subclassed to be used.
Main Methods to be overridden-
1. doInBackground(Params...) *//time consuming operation
2. onPostExecute(Result...)//run on ui thread after
doInBackground
3.onPreExecute() //run on ui thread before doInBackground()
4.onCancelled(Result result) run On ui thread after cancel
23. AsyncTask cont...
5.onProgressUpdate(Progress...values) .
Running AsyncTask -
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute();
Cancelling AsyncTask -
myAsyncTask.cancel(true); //now onCancelled() will be called
instead of onPostExecute() , keep on checking isCancelled()
method in doInBackground inside a loop and break if it is
true.
24. AsyncTask : Order Of Execution (troll)
Depends on API level
1. When it first appeared in Cupcake (1.5) it handled
background operations with a single additional thread (one by
one).
2. In Donut (1.6) it was changed, so that a pool of thread had
begun to be used. And operations could be processed
simultaneously until the pool had been exhausted. In such
case operations were enqueued.
25. AsyncTask : Order Of Execution (troll)
Depends on API level
1. When it first appeared in Cupcake (1.5) it handled
background operations with a single additional thread (one by
one).
2. In Donut (1.6) it was changed, so that a pool of thread had
begun to be used. And operations could be processed
simultaneously until the pool had been exhausted. In such
case operations were enqueued.
27. AsyncTask : Order Of Execution Cont.
3.Since Honeycomb default behavior is switched back to use of
a single worker thread (one by one processing). But the new
method (executeOnExecutor) is introduced to give you a
possibility to run simultaneous tasks if you wish (there two
different standard executors: SERIAL_EXECUTOR and
THREAD_POOL_EXECUTOR).
The way how tasks are enqueued also depends on what
executor you use. In case of a parallel one you are restricted
with a limit of 10 (new
LinkedBlockingQueue<Runnable>(10)). In case of a serial
one you are not limited (new ArrayDeque<Runnable>()).
28. AsyncTask Cont...
If there are less than core pool size threads currently
active and a new job comes in, the executor will create a
new thread and execute it immediately.
If there are at least core pool size threads running, it will
try to queue the job and wait until there is an idle thread
available
If it is not possible to queue the job (the queue can have
a max capacity), it will create a new thread (upto
maximum pool size threads) for the jobs to run in. Non-core
idle threads can eventually be decommissioned
according to a keep-alive timeout parameter.
29. AsyncTask cont...
Before Android 1.6, the core pool size was 1 and the
maximum pool size was 10. Since Android 1.6, the core pore
size is 5, and the maximum pool size is 128. The size of the
queue is 10 in both cases. The keep-alive timeout was 10
seconds before 2.3, and 1 second since then.
This is a very good reason why you should not use
AsyncTasks for long-running operations - it will prevent other
AsyncTasks from ever running.
30. AsyncTask cont...
Before Android 1.6, the core pool size was 1 and the
maximum pool size was 10. Since Android 1.6, the core pore
size is 5, and the maximum pool size is 128. The size of the
queue is 10 in both cases. The keep-alive timeout was 10
seconds before 2.3, and 1 second since then.
This is a very good reason why you should not use
AsyncTasks for long-running operations - it will prevent other
AsyncTasks from ever running.
31. AsyncTask cont...
Before Android 1.6, the core pool size was 1 and the
maximum pool size was 10. Since Android 1.6, the core pore
size is 5, and the maximum pool size is 128. The size of the
queue is 10 in both cases. The keep-alive timeout was 10
seconds before 2.3, and 1 second since then.
This is a very good reason why you should not use
AsyncTasks for long-running operations - it will prevent other
AsyncTasks from ever running.
33. Volley : Design Tradeoff
Volley is a library that makes networking for Android apps easier
and most importantly, faster.
1. Great for RPC – style operation that populate the UI.
2. Fine for background RPC.
3. Terrible for large payloads.
34. Volley Network Framework :
private RequestQueue mRequestQueue;
mRequestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jr = new
JsonObjectRequest(Request.Method.GET,url,null,new
Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i(TAG,response.toString());
parseJSON(response);
va.notifyDataSetChanged();
pd.dismiss();
35. Debugging Using Eclipse
Debugging :
The process of identifying and fixing errors in software
Mainly used to describe run-time errors or incorrect results
36. Eclipse Debugging Features
Breakpoints
Step into
Step over
Step return
Step Filters
Watches
Run to line
Suspend/Resume/Terminate
37. Breakpoints
Breakpoints cause the thread of execution to suspend and
return to the debugger
Setting breakpoints in Eclipse is easy, just double-click the
left margin
38. Step Into
Executes single (highlighted) statement
If statement contains call to method, it steps into the method
To use:
Must be in Debug Perspective
Click from Debug Toolbar or press F5
39. Step Over
Executes single (highlighted) statement
If statement contains method call, the entire method is
executed without stepping through it
To use:
Must be in Debug Perspective
Click from Debug toolbar or press F6
40. Step Return
All statements in current method are executed
Return to where method was called
To use:
Must be in Debug Perspective
Click from Debug toolbar or press F7
41. Step with Filters
User can specify which methods Step Filter will
execute and return from
Usually you would want steps to be made only into
methods of your own classes
To set filters:
Go through Window > Preferences > Java > Debug > Step
Filtering
42. Watches
Watches allow you to view (and sometimes
change) the value of a variable during execution
In Eclipse, watches are set automatically on
variables in scope
Watches can be found in the Eclipse Debug
perspective in the “Variables” window
Eclipse allows you to change the value of variables
dynamically during runtime
43. Run to Line
Equivalent to setting a temporary breakpoint
CTRL+R
44. Suspend/Resume/Terminate
Suspend pauses the current thread of execution and breaks
into the debugger
Resume resumes a suspended application
Terminate stops the program and debugging process
Hot Code Replace – supported by eclipse but not by DVM.