Saturday, 5 November 2011

Introduction of Explicit Intent

Intent is a very good feature provided in Android. The name itself suggests that Intent means some intention to do a specific work. Intent is used for making call to new activity from current activity and sending/Receiving data. Suppose we have an Activity "MainMessageTask" in our app and we want to call "ChildMessageTask" activity from "MainMessageTask". At that time we need to use Intent for making call to child activity. We can also send and receive data from different calling activity with using intent. This is a very first use of Intent in android. " So the Intents are the system messages that will transfer data from Parent Activity to Child Activity and notify about various events done by user. For Example if we remove and insert a memory card on our phone it will notified by intent in android system by developer of the application, and this to be done by using "Implicit Intent". so the main difference between Implicit and Explicit Intent is that...
  • Explicit Intent :- Explicit Intent is used to call another activity by Java class file loading from Parent Activity.
  • Implicit Intent :- Implicit Intent is used to call services without calling java class file within the system messages. For example if we want to call web site in our application then we need to pass that site`s URL from implicit intent with using URI.
But here I am trying to explain you how to use Explicit Intent and how we can send/receive data from different activity. So for that we will just make one simple example which is sending message to child activity from main and also replaying from child activity to main activity. Before we start let first understand some of the basic term, about to be used in our example.
  • Syntax of Intent : Intent <Intent-name> = new Intent ( <application context of current activity>,       <Calling Activity Class name.class> );
  • This is available in class "android.content.Intent" since API Level 1.
  • after making object of intent we need to add data to this object so the syntax for that is...  <Intent-name> . putExtras(<Message>); here putExtras is given in class intent ... "android.content.Intent.putExtras(Bundle extras)" and  method given in class intent is as follows.. "Public Intent putExtras(String,Bundle);" and "Public Intent putExtras(String);"
  • next we need to launch another activity by using two methods 
    1. public void startActivity(Intent <Intent-name>); parameters: <Intent> for intent to start.
    2. public void startActivityForResult(Intent <Intent-name>, int requestCode);                      parameters: <Intent> for intent to start,  <requestCode> >=0, and used after retiring from the child activity specify by developer.
    3. here one question came up in mind is that Which one is going to be best choice out of above two methods in our application? So, answer is very simple if we need to launch an activity as a "Parent-Child" concept then we requires to call method "startActivityForResult(Intent <Intent-name>, int requestCode);" and if we need to launch only activity without getting result back from child activity then we requires to call method  "startActivity(Intent <Intent-name>);" .
    4. In our example we will gona use "startActivityForResult(Intent <Intent-name>, int requestCode); ". Because we launch activity using "Parent-Child" concept. 
  • Let first understand output of our example..
[Figure 01: Main screen for sending messages to child activity]
                [Figure 02: Child screen which responds back to main activity]
[Figure 03: Main screen which gets messages from Child screen]
So the very first thing we will doing is that user generated message is transferred to child activity after clicking on Send Message to Child Activty button. as shown in Figure 01.
[This is our "MainMessageTask.class" activity].

ChildMessageTask.class is called by startActivityForResult(messageIntent); , data is already bundled in messageIntent object by messageIntent.putExtras("Messages"); generated message is displaying on child activity screen. here user also responds back to the main activity. as shown in Figure 02.
[This is our "ChildMessageTask.class" activity], Messages from MainMessageTask.class is fetched by messageIntent.getExtras("Message"); screen message is given back to Main activity as shown in Figure 03.
[This is our MainMessageTask.class activity]. Result by ChildMessageTask is fetch in MainMessageTask by overriding public void onActivityResult(int requestCode,int resultCode,Intent data);
  • So by just understanding above architecture we will going to see complete code of the example...

"Code for Main Activity MainMessageTask.class"


package com.helloworkShop.intentdemo; 

/**
 * This is a Main activity that demonstrates the Explicit Intent concept.

 *
 */

public class MainMessageTask extends Activity implements OnClickListener {
    private Button mySendMessage;
    private EditText myMessage;
    private TextView displayMessageFromChildScreen;
   
    //Methods

    /**
     * onActivityResult - called when the child activity finishes its execution after calling finish method from child activity...
     * This is where you should get data from previous activity [from child activity]
     *
     * Always called by child activity after calling finish method from ChildMessageTask...
     * @param requestCode int
     * @param resultCode int
     * @param data Intent
     */
   

    @Override
    public void onActivityResult(int requestCode,int resultCode,Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            displayMessageFromChildScreen =
            (TextView) findViewById (R.id. displayMessageFromChildActivity);
            String Message= data.getStringExtra("BackResultToMainActivity");
            displayMessageFromChildScreen.setText("Message from Child Activity :- " + Message);
        }
    }

    /**
     * onCreate - called when the activity is first created.
     * This is where you should do all of your normal static set up: create views, bind data to lists, etc.
     *
     * Always followed by onStart().
     *
     */

   
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mmt);
       
        myMessage= (EditText) findViewById(R.id.Messages);
        mySendMessage= (Button) findViewById(R.id.SendMessage);
        mySendMessage.setOnClickListener(this);
    }//end of onCreate method...

      /**
     * onClick - call when the "Send Message to Child Activity" button clicked.
     * This is where you should do all of intent calling procedure.
     *
     */


    @Override
    public void onClick(View button) {
        String strMyMessage=myMessage.getText().toString();
        myMessage.setText("");
        if (button = = mySendMessage){
           // setting up myBundle object for storing messages.
            Bundle myBundle=new Bundle();
            myBundle.putString("MessageFromMainActivity",strMyMessage);
            //Intent created for calling child activity.
             Intent messageIntent = new
             Intent ( MainMessageTask.this.getApplicationContext() , ChildMessageTask.class );
            // putting values of myBundle object to Intent
            messageIntent.putExtras(myBundle);
            // Calling child activity with taking "Parent-Child" concept in mind.
            startActivityForResult(messageIntent, 0);
       }// end of if block...
    }// end of click event...
}// end of main activity...

"Code for Main Activity ChildMessageTask.class"


package com.helloworkshop.intentdemo; 

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * This is a Child activity that demonstrates the Explicit Intent concept.
 * After finishing its execution child sent result back to main to onActivityResult method.
 */

public class ChildMessageTask extends Activity implements OnClickListener {
    private EditText childMessage;
    private Button repalyToMainScreen;
    private TextView displayMainActivityResult;
   
    /**
     * onCreate - called when the activity is first created.
     * This is where you should do all of your normal static set up: create views, bind data to lists, etc.
     *
     * Always followed by onStart().
     *
     */
       
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cmt);
       
        displayMainActivityResult = (TextView) findViewById(R.id.displayMainMessage);
        childMessage =(EditText) findViewById(R.id.replayToMainMessage);
        repalyToMainScreen = (Button) findViewById(R.id.replayToMainScreen);
       
        //this code is getting values from MainScreen Intent...
        //here we specifying bundle and for getting values we uses same name as we,
        //applied in previous bundle name "MessageFromMainActivity".


        Bundle myBundle=this.getIntent().getExtras();
        String MessageFromMainActivity= myBundle.getString("MessageFromMainActivity");
        displayMainActivityResult.setText("Message from MainScreen :- " + MessageFromMainActivity );
        repalyToMainScreen.setOnClickListener(this);


    } // end of onCreate()...


    /**
     * onClick - call when the "Replay to Main Screen" button clicked.
     * This is where you should do all of intent calling procedure.
     *
     */


    @Override
    public void onClick(View replayToMainMessage) {
        String childScreenMessage = childMessage.getText().toString();
        childMessage.setText("");


        if (replayToMainMessage = = repalyToMainScreen){
            Bundle myBundle=new Bundle();
            myBundle.putString("BackResultToMainActivity", childScreenMessage);
            Intent intt=new Intent();
            intt.putExtras(myBundle);
            setResult(RESULT_OK,intt); // setting Result_ok constant so when child finish its execution,

            // parent gets response from this.
            this.finish(); // uses for finishing child activity and get back to main activity by system stack...
        }//end of if block...


    }// end of onClick()... 


}// end of activity class...


  • Here we also need to set up some of the things in "AndroidMenifest.xml file" ... which is given below...
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.helloworkshop.intentdemo"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
       <activity android:name=".MainMessageTask" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"></action>
                <category android:name="android.intent.category.LAUNCHER"></category>
            </intent-filter>
        </activity>

       <activity android:name=".ChildMessageTask" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"></action>
                <category android:name="android.intent.category.DEFAULT"></category>
            </intent-filter>
        </activity>                                                                                                             
</application>
</manifest>
  • What is <intent-filter> ?
    • It is indicating or specifying action on activity which we will going to perform on activity.
    • Specifying data on which we can perform our operations.
  • all of our activities need to register in AndroidMenifest.xml file. First activity is going to be launched is "MainMessageTask". so that in <intent-filter> we specify <action> as a MAIN and <category> as LAUNCHER. So, by default android system is starting our MainMessageTask, activity firstly. using system handled intent.
  • second activity in our app is "ChildMessageTask". so for that in <intent-filter> we specify <action> as a MAIN and <category> as DEFAULT.
  • and XML layout is simple as mentioned in above figures 1 to 3.
So the final conclusion of this article is that Intent is very useful in our apps some of the advantages of intents is given here...
  1. It is loosely couples our application architecture.
  2. It is mainly used for Activate android systems major component like Activity, Services, and also BroadCastReceivers.
  3. Using intent we can start another activity which is already design in our application architecture.
  4. We can also share data from across the system from application to application using Intent.
Thank you for reading this article. Your comments and suggestions are always welcome...

Thursday, 3 November 2011

TYPES OF THREAD MECHANISM IN ANDROID

Thread mechanism in Android is a very good topic for the beginner who wishes to start building a good android application with good responsive time and which runs without too much hangout our app. Generally, this features create a nice end user experience and it will lead acceptance level of apps at very high level, and our clients be happy by using our well responsive application.

So before we start on Android thread mechanism, let us first see some points why we need it in our app?, and without it, Is possible to make our app development easy ? so the some points are coming into my mind are as follows...
  • Android developer team given us Designing Standards and according to that by following those steps we make very high level app experience.
  • Sometimes our application functionality wants to do some tough and time consuming calculations and at that time we are not able to handle all the task done at single thread model, and finally our app leads to unresponsive to end user experience.
  • So the very time consuming work needs to be done at separate user interface thread.
  • Every android application having one "Main" thread. Each of which runs on main user interface thread model and every process needs to communicate with the main thread for successfully tasks implementation. if our processes takes more than of 5 seconds to response to the main thread then android system generates ANR ("Android Not Responding") dialog box like this one...
[Fig:- Android Not Responding Dialog]
  • So the very first reason of using separate thread mechanism in long running calculations is to avoid ANR in our app.
  • Second reason of using thread is that in Game application there were lots of objects communicating to each other and working concurrently at that time we needs to use separate  thread model for updating Game User Interfaces.
  • So the final conclusion for "Why we need Thread in our app?", is that For better responsiveness, For better calculating long running task[Such as Network or Database Operations, Long running services and Updating Location of the User] at separate of Main thread and also to avoid Android ANR dialogs for good end user experiences.

So, by just reading above, We needs to understand one of the thread mechanism available in android and how many types of thread an android provided to developer of the app in sdk, so the answer of this question provided below as per my knowledge...
  1. Android SDK inherits directly Java Thread.
  2. Android Handler Thread.
  3. AsyncTask class thread.
"Android SDK inherits directly Java Thread"
  • Android app developer can directly use the thread available in Java by inheriting package called "java.util.concurrent".
  • This mechanism used only when we need to do some background task without updating user interfaces on this thread, because android does not provide updating User Interface from non Android thread like this one. So this is the drawback. So for overcoming this mechanism android provides some another thread mechanism called "Handler" thread.
"Android Handler Thread"
  • In android Handler is the class given by the sdk, it is used for concurrency, and also updates user interfaces at each time, and also communicate with the Main thread of the application.
  • A handler provides a method for receiving messages and runnable.
  • We requires only one handler object for starting thread and sending result back to handler message queue.
  • So finally... “A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue.”
  • How to use handler in our app... so the code snippets give below...
package com.HelloWorkShopFromGaurangDhorda;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.widget.TextView;

/**
 * This is a simple activity that demonstrates the Handler Thread mechanism.
 *
 */
public class HandlerThreadDemo extends Activity implements Runnable{
   
    private TextView textView;
    private Handler handler;
    private Thread thread;
   
//Methods
/**
 * onCreate - called when the activity is first created.
 * This is where you should do all of your normal static set up: create views, bind data to lists, etc.
 * This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.
 *
 * Always followed by onStart().
 *
 */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pd);
        handler = new Handler();
        textView = (TextView) findViewById(R.id.textView);
        textView.setText("Press Any key to start calculation...");
    }
    /**
 * In response to the being clicked, on any of the screen area of the app this will start a background task 
 * The results will be displayed on the screen.
 *
 * @param keyCode int
 * @param KeyEvent event
 * @return keyCode, event
 */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
            thread = new Thread(this);
            thread.start();
            return super.onKeyDown(keyCode, event);
    }
    /**
 * Perform the task, which is to compute a simple loop through up to 100 and report progress on the UI thread.
 * Return each loop values to UI thread and Main Thread running as per this values...
 *
 */
    @Override
    public void run() {
        try{
            for (int i=1;i<=10;i++){
                objHandler.sendEmptyMessage(i);
                Thread.sleep(2000);
            }
        }
        catch(InterruptedException e){
            e.printStackTrace();
        }
    }
    /**
 * Takes values from run() method by obj.Handler.sendEmptyMessage(i) and values of i will be passes on     *  msg parameter and after that msg parameter is being converted into String object.
 * Return each loop values to UI thread and Main Thread running as per this values... by updating simple     *  TextView values...
 *
 */
    private Handler objHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
                String s=msg.toString();
                textView.setText("calculation completed at :- " + s);
        }
    };
}  

"AsyncTask class thread" 
  • Android AsyncTask Class takes care of Thread management in our application. We must have to extends "AsyncTask" class in our main class activity so that this separate class`s task can be converted into background working model without interfering to main thread....
  • Here main difference in "Handler and AsyncTask" class is that 
    • while running thread in void run() method in handler class we need to pass message to handler class and then we pass that values to main user interface thread.
    • In AsyncTask class android takes care of all thread calling mechanism. So, developer not need to remember anything at all. All calling process done by AsyncTask class. 
  1. Instance of AsyncTask needs to be created in UI thread. Also execute method with parameters should be called from UI thread.
  2. Methods onPostExecute(), onPreExecute() and onProgressUpdate() should not be explicitly called.
  3. Task can be executed only once. 
  • So above points needs to be remember in mind before we apply AsyncTask Class...
  • An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute(), doInBackground(), onProgressUpdate() and onPostExecute().
  • onPreExecute() :- his method is called before doInBackground method is called.
  • doInBackground() :- long running operation goes in this method. When onClick method is executed on click of button, it calls execute method which accepts parameters and automatically calls doInBackground method with the parameters passed. 
  • onProgressUpdate():- This method is invoked by calling publishProgress anytime from doInBackground call this method.
  • onPostExecute():- This method is called after doInBackground method completes processing. Result from doInBackground is passed to this method.
  • We will put one example which we already implemented above for handler...
"code for AsyncTask Demo"

package com.HelloWorkShopFromGaurangDhorda;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

/**
 * This is a simple activity that demonstrates the "AsyncTask" Thread mechanism.
 *
 */

public class AsyncTaskDemo extends Activity implements OnClickListener{
    private TextView textView;
    private Button btnClick;

//Methods
/**
 * onCreate - called when the activity is first created.
 * This is where you should do all of your normal static set up: create views, bind data to lists, etc.
 * This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.
 *
 * Always followed by onStart().
 *
 */


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pd);
        textView = (TextView) findViewById(R.id.textView);
        textView.setText("Press Any key to start calculation...");
        btnClick = (Button) findViewById(R.id.btnClick);
        btnClick.setOnClickListener(this);
    }
   
    /**
 * Perform the task,By clicking button from user interface.

 */
    @Override
    public void onClick(View arg0) {
       
        new asyncdemo().execute(1,1,1);
    }

 /**
 * Asyncdemo class that extends AsysncTask class and it passes 3 Integer Generics types.
* Whole task of  thread is done by android system.
* doInBackground method is automatically called by involing "new asyncdemo().execute(1,1,1);"
* send result back to onProgressUpdate() method by calling publishProgress(i), method in doInBackground * method.
* Automatic updates User Interface and communicate with Main Android Thread...

 */
    public class asyncdemo extends AsyncTask<Integer,Integer,Integer>{

        @Override
        protected Integer doInBackground(Integer... params) {
            // TODO Auto-generated method stub
            int values=0;
           
            try{
            for (int i=1;i<=10;i++){
                publishProgress(i);
                values+=i;
                Thread.sleep(2000);
            }
            }
            catch(InterruptedException e){
                e.printStackTrace();
            }
            return values;
        }
        protected void onProgressUpdate(Integer... progress) {
             textView.setText(progress[0].toString());
         }
       
    }//end of asyncclass...
}// end of main class...

"Final Conclusion"
  • Avoid the Jank (make sure your application is responsive)
    • Don’t block the UI thread
    • Offload long running tasks to background threads
    • Using AsyncTask or ServiceIntent
    • Keep user notified about progress
"I Hope this helps you in better understanding of Thread mechanism available in android sdk and   why we need it in our app?..."