Thursday 27 September 2012

Facebook Page

My Facebook Page for Android Development.
You can latest technology News, Update Information for IT, Quotes...

JUST Like it from  YOUR FACEBOOK ACCOUNT:
http://www.facebook.com/Android4Delopment 

Monday 24 September 2012

Different Types of Started Service


Different Types of Started Service:
       1.       Normal Service without  Thread.
       2.       Service with Single Thread
       3.       Service with Multithreading
       4.       Service with Multithreading (ASYNC TASK)


Normal Service Without Thread:
          1.    Create service tag in your manifest.xml file.
          2.    Implement life cycle function for your service.
          3.    Start your service from your activity and make sure your service will stop.
Example:

Manifest.xml
For developing any service , you need to include service tag in your manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="tara.service"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />
   <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".MyActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
                                <service android:name="MyService"></service>
    </application>
</manifest>


Main.xml 
Create a button in main.xml. When you click the button, service will start.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
  <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />
</LinearLayout>



MyActivity.java

public class MyActivity extends Activity
{
         Intent it = new Intent(this, MyService.class);
    public void onCreate(Bundle savedInstanceState)
{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn = (Button)findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener()
{             
public void onClick(View v)
                                                {             
                                                   startService(it);             
                                                }
                                });
    }
    protected void onDestroy()
    {         
          stopService(it);
    }


MyService.java
public class MyService extends Service
{
                @Override
                public void onCreate()
                {
                                super.onCreate();
                }
                @Override
                public int onStartCommand(Intent intent, int flags, int startId)
                {
                                return super.onStartCommand(intent, flags, startId);
                }
                @Override
                public void onDestroy()
                {             
                                super.onDestroy();
                }
                @Override
                public IBinder onBind(Intent intent)
                {
                                return null;
                }
}


Service With Single Thread:

In service with single thread, you can manually create a thread. You need to use IntentService class, thread will be created automatically.
       1.    Create service tag in your manifest.xml file. Provide the class name (MyService.java). It will extends from IntentService. Then add the un-implemented method.
       2.    Start your service from your activity and make sure your service will stop.

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="tara.service"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".Home"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="MyService"></service>
    </application>

</manifest>

MyService.java

public class MyService extends IntentService
{

                public MyService(String name) {
                                super(name);
                                // TODO Auto-generated constructor stub
                }

                @Override
                protected void onHandleIntent(Intent arg0) {
                                // TODO Auto-generated method stub
                               
                }

}

Here you can’t touch UI beacause onHandleIntent() is running on different thread created by IntentService.


Service With MultiThreading (ASYNC-TASK):

AsyncTask has 4 operations, which are executed by order.

1. onPreExecute() – is invoked before the execution.
2. onPostExecute() - is invoked after the execution.
3. doInBackground() - the main operation. Write your heavy operation here.
4. onProgressUpdate() – Indication to the user on progress. It is invoked every time 
publishProgress() is called.


AsyncTask defines 3 generic types:
AsyncTask<{type of the input}, {type of the update unit}, {type of the result}>
You don’t have to use all of them – simply use ‘Void’ for any of them.


Android developer website also mentions these 4 rules regarding the AsyncTask:
§  The task instance must be created on the UI thread.
§  execute(Params…) must be invoked on the UI thread.
§  Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params…), onProgressUpdate(Progress…) manually.
§  The task can be executed only once (an exception will be thrown if a second execution is attempted.)

The Service class will look like this:

MyService.java

public class MyService extends Service
{
                @Override
                public void onCreate()
                {
                super.onCreate();
                }


                public class MyTask extends AsyncTask<Void, Integer, String>
                {
                                protected void onPreExecute()
                                {
                                                super.onPreExecute();
                                }
                                protected String doInBackground(Void... params)
                                {
                                                return null;
                                }
                                protected void onProgressUpdate(Integer... values)
                                {
                                                super.onProgressUpdate(values);
                                }
                                protected void onPostExecute(String result)
                                {
                                                super.onPostExecute(result);
                                }
                }

               
                @Override
                public int onStartCommand(Intent intent, int flags, int startId)
                {
                return super.onStartCommand(intent, flags, startId);
                }
                @Override
                public void onDestroy()
                {
                                super.onDestroy();
                }
                @Override
                public IBinder onBind(Intent intent) {
                                // TODO Auto-generated method stub
                                return null;
                }
               
}

Friday 21 September 2012

Service


Service

A service is an application component that can run some long running task in the background without the need for a user interface. Some other application component can start the service and this service will then keep on running even if the user switches to another application.

There are two types of service components:

1.     Started Service

2.      Bounded Service

Started Service: 

                                 This service is started by another application component. Once started it keeps running until someone stops the service. This type of service provides several callbacks which is the topic of this tutorial.

Bounded Service:

                               A service is bound when another application component invokes the bindService method. Service binding is used to perform client-server like communication between the service and the caller. These invocations can be performed between different processes as well. Multiple callers can bind to a service. The service stays active until there is atleast one caller bound to the service.

Life Cycle of Started Service

When You are launching any service for first time , on that time it will call onCreate(). If the service is already launched , then from the second time onStartCommand() will call, it won't call onCreate().For started services, there are two additional major modes of operation they can decide to run in, depending on the value they return from onStartCommand(): START_STICKY is used for services that are explicitly started and stopped as needed, while START_NOT_STICKY or START_REDELIVER_INTENT are used for services that should only remain running while processing any commands sent to them. Once the onDestroy() will called, the service will terminate. 

Life Cycle of Bounded Service


Clients can also use Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling onCreate() while doing so), but does not call onStartCommand(). The client will receive the IBinder object that the service returns from its onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the service's IBinder).

Tuesday 18 September 2012

Multi-threading in Android

       This is very important concept for every application

                            (MULTI-THREADING)


Let’s say if you want to do a very long operation when the user pushes a button. If you not put or add any thread in your program, the coding will look like this:

Button btn = (Button)findViewById(R.id.button1);
btn. setOnClickListener(           
             new OnClickListener() 
            {
         
                @Override
                   public void onClick(View v) 
                  {
                     int myapp =longRunningOperation();
                     updateUI(myapp);
                  }
            });

In this program there is a possibility that this program may crash and this is really not a good logic for UI. For every application there is a default thread given by Android and this is known as MainThread or HandlerThread or UI thread.If you want to touch any thread directly,the program will crash.


Now we check it in another way. Now we create a thread and run this program under that thread.
Lets’ see what happens if we use a thread for long running operation:

Button btn = (Button)findViewById(R.id.button1);
btn. setOnClickListener(           
             new OnClickListener() 
            {
         
                @Override
                   public void onClick(View v) 
                  {
                     (new Thread(new Runnable() {
                     
                    @Override
                    public void run() 
                   {
                                 int myapp =longRunningOperation();
                                 updateUI(myapp);
                   }
                })).start();

                  }
            });

But when executing this program, again the program crashes. For details you can check in LogCat.

ERROR/AndroidRuntime(210): FATAL EXCEPTION: Thread-8
ERROR/AndroidRuntime(210): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
ERROR/AndroidRuntime(210): at ...

Here you are touching the UI directly that’s why it’s crashing.You can’t touch UI directly from other thread. If you want to touch UI, you need to take permission from other thread. This is achieved by inter thread communication. 


Solution for the above Problem:

Handler:
Now you need to know about the Handler Thread in Android.In the above program we are calling long running operation that means we are updating the operation for long time. The Handler class can solve this problem.The  Handler class can update the user interface. A Handler provides methods for receiving instances of the  Message  or  Runnable class. The Handler is the middleman between a new thread and the message queue.

Example:
1. Assume there is a queue for messages. Each messages to be handled.
2. Threads can add the messages.
3. Only a single thread pulls the messages one by one from the queue.



Now Run the new thread and use the handler to send messages for ui changes.

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 = longRunningOperation();
         
        myHandler.sendMessage(msg);
    }
})).start();

keep in mind that updating the UI should still be a short operation, since the UI freezes during the updating process.



Looper:
If we want to dive a bit deeper into the android mechanism we have to understand what is a Looper.
We have talked about the message queue that the main thread pulls messages and runnables from it and executes them.
We also said that each handler you create has a reference to this queue.
What we haven’t said yet is that the main thread has a reference to an object named Looper.
The Looper gives the Thread the access to the message queue.
Only the main thread has executes to the Looper by default.

(new Thread(new Runnable() {

                    @Override
                    public void run() {

                        Looper.prepare();
                        innerHandler = new Handler();
                                 
                        Message message = innerHandler.obtainMessage();
                        innerHandler.dispatchMessage(message);
                        Looper.loop();
                    }
                })).start();



ASYNC Task:

AsyncTask has 4 operations, which are executed by order.
1. onPreExecute() – is invoked before the execution.
2. onPostExecute() - is invoked after the execution.
3. doInBackground() - the main operation. Write your heavy operation here.
4. onProgressUpdate() – Indication to the user on progress. It is invoked every time publishProgress() is called.

AsyncTask defines 3 generic types:
AsyncTask<{type of the input}, {type of the update unit}, {type of the result}>
You don’t have to use all of them – simply use ‘Void’ for any of them.

Android developer website also mentions these 4 rules regarding the AsyncTask:
The task instance must be created on the UI thread.
execute(Params…) must be invoked on the UI thread.
Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params…), onProgressUpdate(Progress…) manually.
The task can be executed only once (an exception will be thrown if a second execution is attempted.)


class MyAsyncTask extends AsyncTask<Integer, String, Long> {
         
        @Override
        protected Long doInBackground(Integer... params) {
             
            long start = System.currentTimeMillis();
            for (Integer integer : params) {
                publishProgress("start processing "+integer);
                doLongOperation();
                publishProgress("done processing "+integer);
            }
             
            return start - System.currentTimeMillis();
        }

         
         
        @Override
        protected void onProgressUpdate(String... values) {
            updateUI(values[0]);
        }
         
        @Override
        protected void onPostExecute(Long time) {
            updateUI("Done with all the operations, it took:" +
                                     time + " millisecondes");
        }

        @Override
        protected void onPreExecute() {
            updateUI("Starting process");
        }
         
         
        public void doLongOperation() {
             
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
             
        }
         
    }

Saturday 15 September 2012

Threading in Android


Android modifies the user interface and handles input events from one single user interface thread which is also called the main thread.If the programmer does not use any concurrency constructs, all code of an Android application runs in this thread.If you perform a long lasting operation, e.g. loading a file or accessing data from the Internet, the user interface of your Android Application will block until the corresonding code has finished.

To provide a good user experience all potentially slow running operations in an Android application should run asynchronously, e.g. via some way of concurrency constructs of the Java language or the Android framework. This includes all potential slow operations, like network, file and database access and complex calculations.

This single thread model can yield poor performance in Android applications that do not consider the implications. Since everything happens on a single thread performing long operations, like network access or database queries, on this thread will block the whole user interface. No event can be dispatched, including drawing events, while the long operation is underway. From the user's perspective, the application appears hung. Even worse, 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.

For this reason we use Handler Threads in Android.In Handler Thread basically there are two components:

1.     Looper

2.     Message Queue.

In Java environment looper is in passive mode but have Message Queue.A given handler have only one looper and one message queue.If anybody wants to communicate with application, they have send a message and push that message into message queue of that handler  thread.

Java Threading


Before going to discuss about threading in android , you need to learn how threading works in java. This is very important concept in all application development.

All programmers are familiar with writing sequential programs. You've probably written a program that displays "Hello World!", or sorts a list of names, or computes a list of prime numbers. These are sequential programs: each has a beginning, an execution sequence, and an end. At any given time during the runtime of the program there is a single point of execution.
A thread is similar to the sequential programs described above: a single thread also has a beginning, an end, a sequence, and at any given time during the runtime of the thread there is a single point of execution. However, a thread itself is not a program. It cannot run on its own, but runs within a program.
 A thread is a single sequential flow of control within a program.
Life Cycle of a Thread:
Above mentioned stages are explained here:
·         New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.
·         Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.
·         Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.
·         Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
·         Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.

Thread Priorities:

Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.
Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependentant.

Creating a Thread:

Java defines two ways in which this can be accomplished:
·         You can implement the Runnable interface.
·         You can extend the Thread class, itself.

Create Thread by Implementing Runnable:

The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable, a class need only implement a single method called run( ), which is declared like this:
public void run( )
You will define the code that constitutes the new thread inside run() method. It is important to understand that run() can call other methods, use other classes, and declare variables, just like the main thread can.
After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class. Thread defines several constructors. The one that we will use is shown here:
Thread(Runnable threadOb, String threadName);
Here threadOb is an instance of a class that implements the Runnable interface and the name of the new thread is specified by threadName.
After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. The start( ) method is shown here:
void start( );

Example:

Here is an example that creates a new thread and starts it running:
// Create a new thread.
class NewThread implements Runnable {
   Thread t;
   NewThread() {
      // Create a new, second thread
      t = new Thread(this, "Demo Thread");
      System.out.println("Child thread: " + t);
      t.start(); // Start the thread
   }
   
   // This is the entry point for the second thread.
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Child Thread: " + i);
            // Let the thread sleep for a while.
            Thread.sleep(500);
         }
     } catch (InterruptedException e) {
         System.out.println("Child interrupted.");
     }
     System.out.println("Exiting child thread.");
   }
}
 
class ThreadDemo {
   public static void main(String args[]) {
      new NewThread(); // create a new thread
      try {
         for(int i = 5; i > 0; i--) {
           System.out.println("Main Thread: " + i);
           Thread.sleep(1000);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread interrupted.");
      }
      System.out.println("Main thread exiting.");
   }
}
This would produce following result:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

Create Thread by Extending Thread:

The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class.
The extending class must override the run( ) method, which is the entry point for the new thread. It must also call start( ) to begin execution of the new thread.

Example:

Here is the preceding program rewritten to extend Thread:
// Create a second thread by extending Thread
class NewThread extends Thread {
   NewThread() {
      // Create a new, second thread
      super("Demo Thread");
      System.out.println("Child thread: " + this);
      start(); // Start the thread
   }
 
   // This is the entry point for the second thread.
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Child Thread: " + i);
                                              // Let the thread sleep for a while.
            Thread.sleep(500);
         }
      } catch (InterruptedException e) {
         System.out.println("Child interrupted.");
      }
      System.out.println("Exiting child thread.");
   }
}
 
class ExtendThread {
   public static void main(String args[]) {
      new NewThread(); // create a new thread
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Main Thread: " + i);
            Thread.sleep(1000);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread interrupted.");
      }
      System.out.println("Main thread exiting.");
   }
}
This would produce following result:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.