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?..."

Thursday, 29 September 2011

My Proposed Career Path and Also Thankfull to ALL


I am graduated from Bhavnagar University in BCA and I am pursuing MCA[Present on fourth semester], and  after that I also want to do some challenging work in my professional life like all good personalities.

But firstly, I would like to thanks some of personalities. All are helping me up-to now and makes me happy and builds up some positive attitude in me during my education...

1. My parents
2. My gurus, without them I do not think all its been possible.
  • Mr. Patel Sir - Principal in Shree Swaminarayan College of Computer Science Bhavnagar.
  • Mr. Kalpesh Sir - Working as Head of Department in Shree Swaminarayan College of Computer Science, Bhavnagar
  • Mr. Pratik Gohil - Working as Sr. Asst. Professor in MCA Department with S. V. Institute    of Computer Studies, Kadi.
  • Mr. Rajiv Parikh - Working as Professor in Shree Swaminarayan College of Computer Science, Bhavnagar.
  • and my all gurus who helps me directly or indirectly....
3. My Friends thanks for their warmly help and support. 
4. Last but not least All of my well wisher.

While from now onwards I wish to start my career in Information Technology, for that some of the basic professional concepts must have in me and also a simple positive attitude towards my professional IT Career.
For that something comes to my mind and I have curious to follow it throughout my career.

"Below are my proposed Career Path"
  • Programmer
  • Analyst/Programmer
  • Team Leader
  • Project Manager
  • Systems Development Manager
  • Executive Director - Systems
  • CIO [Chief Information Officer]
"Interested in New Technology Learning"
  • Mobile Computing using Android Technologies
  • Mobile Cloud Computing 
  • Interested in developing some innovative apps in mobile technologies.

Thursday, 8 September 2011

App to find nearest location using GPS in android


One of the major functionality provided by the smartphone is GPS [Global Positioning System] enable. I never realized that interacting with GPS functionality is so easy until I worked with it. This article is a way to help people realize the same.This article is targeted to a beginner who wants to implement GPS functionality and work with Google Maps API as well. 
" Challenges During getting location into Google maps"
  • First Question arise in mind is that When we want to get current location in our apps then how our phone  find out Geo Co-Ordinates [Latitude and Longitude] values?
    • With respect to this question as per my knowledge phone gets current location using different quipped devices and methods like.... GPS, USING NETWORK PROVIDER, AND OFF COURSE USING INTERNET CONNECTION.  
  • Second Question arise in mind is that How it all be possible?
    •  With respect to this question, we have basic knowledge of android sdk, how to create simple application in android and have conceptually clear in different component of project like Activity, Intents, Views, XML Viewer, Activity Life cycle, basic knowledge of AndroidManifest.xml, Emulator, basic knowledge of Eclipse, and last but not least is Android Emulator, and DDMS, Because without it we might be not able to build this application.
  • For rest of answer of your questions please go through this tutorial and if you have any doubt then comment it at last of article...
Before proceed we getting knowledge about Google api key. The first and foremost thing is getting a Google Maps API key. Getting one is relatively easy but it requires our application to be signed with a certificate and notify Google about Hash (MD5) fingerprint of the certificate. Now, the process can be further divided into two parts: 
[1] Getting google map api key (fist get fingerprint key values and after that use it for getting map api key.)
[2] After getting google map api key used it into your android application for authorizing your app. for that you have to put whole key into xml file of your view.


Now some Questions are arises in mind like How to get map api key? How to use it ? So, the answer is given below.


We create new certificate using keytool.exe available in your java\bin directory, into your command prompt type following command...

keytool -list -alias androiddebugkey -keystore "your path put here\debug.keystore" -storepass android -keypass android



In above command we used one file name is "debug.keystore", is used for using app in debug mode and we get md5 Google map api key and whole debugging structure stored or located into your own file. after running above command you will get your fingerprint md5 Google map key. after that Go to google api signup page and use your fingerprint key for getting apikey.


After that Create New Android Project, Create new AVD with target mode =  Google APIs


after that first you have to setup your geo location in emulator, because if you tested your app in emulator then it will not directly get current location, we have to supply it explicitly.


for that open your cmd, type "telnet localhost <your emulator port no like... 5554>"
and now set your current location into your phones GPS by applying command  
geo fix <Latitude value> <Longitude value>


Now first step is open your main.xml file and put code given below


<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainlayout"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <com.google.android.maps.MapView
        android:id="@+id/mapview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:clickable="true"
        android:enabled="true"
        android:apiKey="Your APIKEY goes here..."
    />
</RelativeLayout>


Second step is to update your AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.gaurang.android.MapView"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
    <uses-permission android:name="android.permission.INTERNET" />
   
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name="com.gaurang.android.MapsViews.MapsView"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
<uses-library android:required="true" android:name="com.google.android.maps">
</uses-library>
    </application>
</manifest>


Third step is to code for our application so open your Activity.java file

package com.gaurang.android.MapsViews;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.gaurang.android.MapView.R;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;


public class MapsView extends MapActivity {
    /** Called when the activity is first created. */
    private MapController mapController;
    private MapView mapView;
    private LocationManager locationManager;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); //// bind the layout to the activity
       
     // create a map view
        RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.mainlayout);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        mapView.setStreetView(true);
        mapController = mapView.getController();
        mapController.setZoom(16); // Zoon 1 is world view
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, new GeoUpdateHandler());
    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
   
    public class GeoUpdateHandler implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {
            if (location !=null){
                //int lat = (int) (location.getLatitude() * 1E6);
                //int lng = (int) (location.getLongitude() * 1E6);
                GeoPoint point = new GeoPoint(
                          (int) (location.getLatitude() * 1E6),
                          (int) (location.getLongitude() * 1E6));
               
                Toast.makeText(getBaseContext(),
                          "Latitude: " + location.getLatitude() +
                          " Longitude: " + location.getLongitude(),
                          Toast.LENGTH_LONG).show();
               
                Log.i("GPS Cordinates", "LAT= "+ location.getLatitude() + "LONG= "+ location.getLongitude());
               
                //mapController.animateTo(point);
                    mapController.setCenter(point);
                mapController.setZoom(16);
                mapView.invalidate();
            }
        }
           
        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    }   
}

Now test your app into your emulator and see the map of your current(nearest) location. You also required to do change in above code as per your settings and packages files and also as per your project and activity name.

The class "LocationManager" provides access to the location.You can register a "LocationListener" with the "LocationManager" and will receive periodic updates about the geoposition. The class "LocationProvider" is the superclass of the different location providers which deliver the information about the current location. 

Each and every time when user changes location of phone then automatically fires  public void onLocationChanged(Location location) method and what we written into this whole runs successfully. onLocationChanged(Location location) method is given into the class LocationListner and we used this method as a method Override concepts.


So i think from my side i explained you with short content but after reading this i wish that it will be useful to various beginner developer like me so 
"Keep sharing your knowledge and also use your knowledge"

Thanks to all who read this content.

Tuesday, 6 September 2011

"Some Things To Always Remember OR Some Things Can Change Your Life"

Your presence is a present to the world.
You are unique and one of a kind.
Your life can be what you want it to be.
Take the days just one at a time. 

Count your blessings, not your troubles.
You will make it through whatever comes along.
Within you are so many answers.


Understand, have courage, be strong.
Do not put limits on yourself.

So many dreams are waiting to be realized.
Decisions are too important to leave to chance.
Reach for your peak, your goal and your prize. 

Nothing wastes more energy than worrying.
The longer one carries a problem the heavier it gets.

Do not take things too seriously.
Live a life of serenity, not a life of regrets. 

Remember that a little love goes a long way.
Remember that a lot … goes forever.
Remember that friendship is a wise investment.
Life’s treasure are people together. 

Realize that it is never too late.
Do ordinary things in an extraordinary way.
Have hearth and hope and happiness.
Take the time to wish upon a start. 

AND DO NOT EVER FORGET ….
FOR EVEN A DAY HOW VERY SPECIAL YOU ARE !


  • We all lives in real world, and we are human beings so basic nature of being human we always thinks much more so while thinking why we not think in appropriate way, Why we not think that  theres always some imagination "DOT" behind every phase of life, But not all understand it, even I am also, But the only thing in our hand is that "Try...Try... after Every Try" , and once we definitely worth our expectations... and if it could not be your worth so again try...................................................

Monday, 5 September 2011

What should be in android apps developer?

  • "Android Apps Basics".  
  • Android is gaining more and more popularity nowadays. Every fresher mobile developer wants to know about android and also about what should be in fresher android apps. developer.
  • Before start thinking on Android apps development We should be well versed in Core Java concepts and off-course in Oops concepts also. 
  • So start thinking after that on some android stuff. for that we can able to know what is android? how we use it as a Mobile apps development? and also Do start searching over internet resources and we will definitely find out some interesting new things which we want to know...
  • So For Learning Android our first step is to visit site... 
  • After that understand the Features, Architecture, Application Framework, etc... 
  • http://developer.android.com/guide/topics/fundamentals.html , just go through this link and you will able to easily understand what is the whole fundamentals concepts behind android.
  • But the actual Question is still pending What should be in android apps developer?...
    • So the answer is given below as per my thinking and I followed these way also...
      • [I]   Develop your working environment for android apps development for that we    required Eclipse Latest Compatible version  for android SDK.                                       
      • [II]  We need to download Android SDK. (download it from above site link)
      • [III] Install latest JAVA JDK. (install JDK not only JRE) Because of only JRE is not installed whole java in your computer. Main difference between JRE and JDK is that JDK is used for Developing Java Programs and JRE is used for Running java programs which is already available in every computer by Operating System). 
      1. After that follow the instructions written on Android Developer sites. and set up your development environment. If you facing any problem while setting up Ask me may I solve your problem.
      2. After that start developing your First Hello World app in eclipes .....
        • for that Go to File -> New-> AndroidProject and create new project on android by entering details about your apps.     
 What is Activity? 
"Relation between Activity and View"
Defines a View to be displayed in its window, Its a presentation layer. Activity
is Screen which user uses it for input. An
application can have more than one activity. Each activity extends android.app.Activity, onCreate() method is overridden to create a user view - the actual layout is displayed over here.

What is View? 
A View is the visible part of the activity
Defined in an XML layout file (or in code)

What is Intent?
Starts another activity ("opens a new window")
Can pass data to the started activity
Can even start activities from another app

 What is Services?
Services runs in background and without user-interface. It extends service class. Typically used to run a services that need to be running even if the screen is closed
 
"The new Android Project created the above files and folders"
 Structure of Android Manifest.XML file


 I will be back with Further more content on this [Coming Soon...]