Hi Friends, if you like my blog please give your valuable comments it will help to improve my blog content and enthusiasm to write a lot in android World.

Wednesday, August 21, 2013

Detect Current Location in Android Using GPS/NETWORK Provider


Using the Location Manager class, we can obtain periodic updates of the device's geographical locations as well as fire an intent when it enters the proximity of a certain location.


1. Obtain a reference to the LocationManager class using the getSystemService() method.
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


2. Create a LocationListener Class for notify the location changes.
Our MyLocationListener class should implements the LocationListener abstract class. There are four methods that you need to override in this implementation:
    * onLocationChanged(Location location): This method is called when the location has changed.
    * onProviderDisabled(String provider): This method is called when the provider is disabled by the user.
    * onProviderEnabled(String provider): This method is called when the provider is enabled by the user.
    * onStatusChanged(String provider, int status, Bundle extras): This method is called when the provider status changes.


3. To be notified whenever there is a change in location, you need to register for a request for changes in locations so that your program can be notified periodically. This is done via the requestLocationUpdates() method (see Listing 1).

This method takes in four parameters:
    * provider: The name of the provider with which you register
    * minTime: The minimum time interval for notifications, in milliseconds.
    * minDistance: The minimum distance interval for notifications, in meters.
    * listener: An object whose onLocationChanged() method will be called for each location update.

4. Set the following User-Permission  in androidmanifest.xml
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>


Sample Code :
package com.cureent;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

public class TestActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener {

    private EditText editTextShowLocation;
    private Button buttonGetLocation;
    private ProgressBar progress;

    private LocationManager locManager;
    private LocationListener locListener = new MyLocationListener();

    private boolean gps_enabled = false;
    private boolean network_enabled = false;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        editTextShowLocation = (EditText) findViewById(R.id.editText1);

        progress = (ProgressBar) findViewById(R.id.progressBar1);
        progress.setVisibility(View.GONE);

        buttonGetLocation = (Button) findViewById(R.id.button1);
        buttonGetLocation.setOnClickListener(this);

        locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    }

    @Override
    public void onClick(View v) {
        progress.setVisibility(View.VISIBLE);
        // exceptions will be thrown if provider is not permitted.
        try {
            gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
        }
        try {
            network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
        }

        // don't start listeners if no provider is enabled
        if (!gps_enabled && !network_enabled) {
            AlertDialog.Builder builder = new Builder(this);
            builder.setTitle("Attention!");
            builder.setMessage("Sorry, location is not determined. Please enable location providers");
            builder.setPositiveButton("OK", this);
            builder.setNeutralButton("Cancel", this);
            builder.create().show();
            progress.setVisibility(View.GONE);
        }

        if (gps_enabled) {
            locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
        }
        if (network_enabled) {
            locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
        }
    }

    class MyLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                // This needs to stop getting the location data and save the battery power.
                locManager.removeUpdates(locListener);

                String londitude = "Londitude: " + location.getLongitude();
                String latitude = "Latitude: " + location.getLatitude();
                String altitiude = "Altitiude: " + location.getAltitude();
                String accuracy = "Accuracy: " + location.getAccuracy();
                String time = "Time: " + location.getTime();

                editTextShowLocation.setText(londitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
                progress.setVisibility(View.GONE);
            }
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        if(which == DialogInterface.BUTTON_NEUTRAL){
            editTextShowLocation.setText("Sorry, location is not determined. To fix this please enable location providers");
        }else if (which == DialogInterface.BUTTON_POSITIVE) {
            startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }
    }

}

 Reverse geocoding:


package com.exercise.AndroidFromLocation;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidFromLocation extends Activity {

double LATITUDE = 37.42233;
double LONGITUDE = -122.083;

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       TextView myLatitude = (TextView)findViewById(R.id.mylatitude);
       TextView myLongitude = (TextView)findViewById(R.id.mylongitude);
       TextView myAddress = (TextView)findViewById(R.id.myaddress);
      
       myLatitude.setText("Latitude: " + String.valueOf(LATITUDE));
       myLongitude.setText("Longitude: " + String.valueOf(LONGITUDE));
      
       Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);

       try {
  List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
 
  if(addresses != null) {
   Address returnedAddress = addresses.get(0);
   StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
   for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
    strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
   }
   myAddress.setText(strReturnedAddress.toString());
  }
  else{
   myAddress.setText("No Address returned!");
  }
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  myAddress.setText("Canont get Address!");
 }

   }
}


Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >
<TextView 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="@string/hello"
   />
<TextView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Location"
   android:background="#505050"
   />
<TextView
   android:id="@+id/mylatitude"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<TextView
   android:id="@+id/mylongitude"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<TextView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Address"
   android:background="#505050"
   />
<TextView
   android:id="@+id/myaddress"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
</LinearLayout>



1 comment:

  1. i need source code sir,,,my mail id sasikumar1190@gmail.com

    ReplyDelete