How To Get Current Location GPS Using GPSTracker In Android

This project consists of two part, First get current location using GPSTracker to get location by Latitude and Longitude. The location Base on Device or Mobile current location with turn on The GPS on settting Device. Lets begin to build GPSTracker project, First create new android aplication project.

Create new java class in your project package

GPSTracker.java
 package sepdian.blog.gpstracker;  
   
 import java.io.IOException;  
 import java.util.List;  
 import java.util.Locale;  
   
 import android.app.AlertDialog;  
 import android.app.Service;  
 import android.content.Context;  
 import android.content.DialogInterface;  
 import android.content.Intent;  
 import android.location.Address;  
 import android.location.Geocoder;  
 import android.location.Location;  
 import android.location.LocationListener;  
 import android.location.LocationManager;  
 import android.os.Bundle;  
 import android.os.IBinder;  
 import android.provider.Settings;  
 import android.util.Log;  
   
 /**  
  * Create this Class from tutorial :   
  * http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial  
  *   
  * For Geocoder read this : http://stackoverflow.com/questions/472313/android-reverse-geocoding-getfromlocation  
  *   
  */  
   
 public class GPSTracker extends Service implements LocationListener {  
   
   // Get Class Name  
   private static String TAG = GPSTracker.class.getName();  
   
   private final Context mContext;  
   
   // flag for GPS Status  
   boolean isGPSEnabled = false;  
   
   // flag for network status  
   boolean isNetworkEnabled = false;  
   
   // flag for GPS Tracking is enabled   
   boolean isGPSTrackingEnabled = false;  
   
   Location location;  
   public double latitude;  
   public double longitude;  
   
   // How many Geocoder should return our GPSTracker  
   int geocoderMaxResults = 1;  
   
   // The minimum distance to change updates in meters  
   private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters  
   
   // The minimum time between updates in milliseconds  
   private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute  
   
   // Declaring a Location Manager  
   protected LocationManager locationManager;  
   
   // Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information  
   private String provider_info;  
   
   public GPSTracker(Context context) {  
     this.mContext = context;  
     getLocation();  
   }  
   
   /**  
    * Try to get my current location by GPS or Network Provider  
    */  
   public void getLocation() {  
   
     try {  
       locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);  
   
       //getting GPS status  
       isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);  
   
       //getting network status  
       isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);  
   
       // Try to get location if you GPS Service is enabled  
       if (isGPSEnabled) {  
         this.isGPSTrackingEnabled = true;  
   
         Log.d(TAG, "Application use GPS Service");  
   
         /*  
          * This provider determines location using  
          * satellites. Depending on conditions, this provider may take a while to return  
          * a location fix.  
          */  
   
         provider_info = LocationManager.GPS_PROVIDER;  
   
       } else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled  
         this.isGPSTrackingEnabled = true;  
   
         Log.d(TAG, "Application use Network State to get GPS coordinates");  
   
         /*  
          * This provider determines location based on  
          * availability of cell tower and WiFi access points. Results are retrieved  
          * by means of a network lookup.  
          */  
         provider_info = LocationManager.NETWORK_PROVIDER;  
   
       }   
   
       // Application can use GPS or Network Provider  
       if (!provider_info.isEmpty()) {  
         locationManager.requestLocationUpdates(  
           provider_info,  
           MIN_TIME_BW_UPDATES,  
           MIN_DISTANCE_CHANGE_FOR_UPDATES,   
           this  
         );  
   
         if (locationManager != null) {  
           location = locationManager.getLastKnownLocation(provider_info);  
           updateGPSCoordinates();  
         }  
       }  
     }  
     catch (Exception e)  
     {  
       //e.printStackTrace();  
       Log.e(TAG, "Impossible to connect to LocationManager", e);  
     }  
   }  
   
   /**  
    * Update GPSTracker latitude and longitude  
    */  
   public void updateGPSCoordinates() {  
     if (location != null) {  
       latitude = location.getLatitude();  
       longitude = location.getLongitude();  
     }  
   }  
   
   /**  
    * GPSTracker latitude getter and setter  
    * @return latitude  
    */  
   public double getLatitude() {  
     if (location != null) {  
       latitude = location.getLatitude();  
     }  
   
     return latitude;  
   }  
   
   /**  
    * GPSTracker longitude getter and setter  
    * @return  
    */  
   public double getLongitude() {  
     if (location != null) {  
       longitude = location.getLongitude();  
     }  
   
     return longitude;  
   }  
   
   /**  
    * GPSTracker isGPSTrackingEnabled getter.  
    * Check GPS/wifi is enabled  
    */  
   public boolean getIsGPSTrackingEnabled() {  
   
     return this.isGPSTrackingEnabled;  
   }  
   
   /**  
    * Stop using GPS listener  
    * Calling this method will stop using GPS in your app  
    */  
   public void stopUsingGPS() {  
     if (locationManager != null) {  
       locationManager.removeUpdates(GPSTracker.this);  
     }  
   }  
   
   /**  
    * Function to show settings alert dialog  
    */  
   public void showSettingsAlert() {  
     AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);  
   
     //Setting Dialog Title  
     alertDialog.setTitle("Title");  
   
     //Setting Dialog Message  
     alertDialog.setMessage("Message");  
   
     //On Pressing Setting button  
     alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {  
   
       @Override  
       public void onClick(DialogInterface dialog, int which)   
       {  
         Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);  
         mContext.startActivity(intent);  
       }  
     });  
   
     //On pressing cancel button  
     alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {  
   
       @Override  
       public void onClick(DialogInterface dialog, int which)   
       {  
         dialog.cancel();  
       }  
     });  
   
     alertDialog.show();  
   }  
   
   /**  
    * Get list of address by latitude and longitude  
    * @return null or List<Address>  
    */  
   public List<Address> getGeocoderAddress(Context context) {  
     if (location != null) {  
   
       Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);  
   
       try {  
         /**  
          * Geocoder.getFromLocation - Returns an array of Addresses   
          * that are known to describe the area immediately surrounding the given latitude and longitude.  
          */  
         List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);  
   
         return addresses;  
       } catch (IOException e) {  
         //e.printStackTrace();  
         Log.e(TAG, "Impossible to connect to Geocoder", e);  
       }  
     }  
   
     return null;  
   }  
   
   /**  
    * Try to get AddressLine  
    * @return null or addressLine  
    */  
   public String getAddressLine(Context context) {  
     List<Address> addresses = getGeocoderAddress(context);  
   
     if (addresses != null && addresses.size() > 0) {  
       Address address = addresses.get(0);  
       String addressLine = address.getAddressLine(0);  
   
       return addressLine;  
     } else {  
       return null;  
     }  
   }  
   
   /**  
    * Try to get Locality  
    * @return null or locality  
    */  
   public String getLocality(Context context) {  
     List<Address> addresses = getGeocoderAddress(context);  
   
     if (addresses != null && addresses.size() > 0) {  
       Address address = addresses.get(0);  
       String locality = address.getLocality();  
   
       return locality;  
     }  
     else {  
       return null;  
     }  
   }  
   
   /**  
    * Try to get Postal Code  
    * @return null or postalCode  
    */  
   public String getPostalCode(Context context) {  
     List<Address> addresses = getGeocoderAddress(context);  
   
     if (addresses != null && addresses.size() > 0) {  
       Address address = addresses.get(0);  
       String postalCode = address.getPostalCode();  
   
       return postalCode;  
     } else {  
       return null;  
     }  
   }  
   
   /**  
    * Try to get CountryName  
    * @return null or postalCode  
    */  
   public String getCountryName(Context context) {  
     List<Address> addresses = getGeocoderAddress(context);  
     if (addresses != null && addresses.size() > 0) {  
       Address address = addresses.get(0);  
       String countryName = address.getCountryName();  
   
       return countryName;  
     } else {  
       return null;  
     }  
   }  
   
   @Override  
   public void onLocationChanged(Location location) {  
   }  
   
   @Override  
   public void onStatusChanged(String provider, int status, Bundle extras) {  
   }  
   
   @Override  
   public void onProviderEnabled(String provider) {  
   }  
   
   @Override  
   public void onProviderDisabled(String provider) {  
   }  
   
   @Override  
   public IBinder onBind(Intent intent) {  
     return null;  
   }  
 }  
   
   

Update your activity_main.xml with code below

activity_main.xml
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:paddingBottom="@dimen/activity_vertical_margin"  
   android:paddingLeft="@dimen/activity_horizontal_margin"  
   android:paddingRight="@dimen/activity_horizontal_margin"  
   android:paddingTop="@dimen/activity_vertical_margin"  
   tools:context="sepdian.blog.gpstracker.MainActivity"   
   android:orientation="vertical"  
   android:gravity="center">  
   
   <TextView android:id="@+id/latitude"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="@string/hello_world"   
     android:padding="4dp"  
     android:textSize="16dp"/>  
     
   
   <TextView android:id="@+id/longitude"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="@string/hello_world"   
     android:padding="4dp"  
     android:textSize="16dp"/>  
     
   <Button android:id="@+id/button"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Get Location"/>  
   
 </LinearLayout>  
   

MainActivity.java
 package sepdian.blog.gpstracker;  
   
 import android.app.Activity;  
 import android.os.Bundle;  
 import android.view.Menu;  
 import android.view.MenuItem;  
 import android.view.View;  
 import android.view.View.OnClickListener;  
 import android.widget.Button;  
 import android.widget.TextView;  
   
   
 public class MainActivity extends Activity {  
   
  TextView longitude, latitude;  
  private GPSTracker gpsTracker;  
  private Button button;  
    
  @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
       
     latitude = (TextView) findViewById(R.id.latitude);  
     longitude = (TextView) findViewById(R.id.longitude);  
     button = (Button) findViewById(R.id.button);  
       
     gpsTracker = new GPSTracker(this);  
       
     button.setOnClickListener(new OnClickListener() {  
      
    @Override  
    public void onClick(View v) {  
     // TODO Auto-generated method stub  
     if (gpsTracker.getIsGPSTrackingEnabled()){  
        latitude.setText("Latitude : "+String.valueOf(gpsTracker.latitude));  
        longitude.setText("Longitude : "+String.valueOf(gpsTracker.longitude));  
       }  
    }  
   });  
   }  
   
   @Override  
   public boolean onCreateOptionsMenu(Menu menu) {  
     // Inflate the menu; this adds items to the action bar if it is present.  
     getMenuInflater().inflate(R.menu.main, menu);  
     return true;  
   }  
   
   @Override  
   public boolean onOptionsItemSelected(MenuItem item) {  
     // Handle action bar item clicks here. The action bar will  
     // automatically handle clicks on the Home/Up button, so long  
     // as you specify a parent activity in AndroidManifest.xml.  
     int id = item.getItemId();  
     if (id == R.id.action_settings) {  
       return true;  
     }  
     return super.onOptionsItemSelected(item);  
   }  
 }  
   

Add user-permission in your android manifest.xml

manifest.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
   package="sepdian.blog.gpstracker"  
   android:versionCode="1"  
   android:versionName="1.0" >  
   
    
   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />  
     
   <uses-sdk  
     android:minSdkVersion="11"  
     android:targetSdkVersion="21" />  
   
   <application  
     android:allowBackup="true"  
     android:icon="@drawable/ic_launcher"  
     android:label="@string/app_name"  
     android:theme="@style/AppTheme" >  
     <activity  
       android:name=".MainActivity"  
       android:label="@string/app_name" >  
       <intent-filter>  
         <action android:name="android.intent.action.MAIN" />  
   
         <category android:name="android.intent.category.LAUNCHER" />  
       </intent-filter>  
     </activity>  
   </application>  
   
 </manifest>  
   

Source : http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial
Source Geocoder : http://stackoverflow.com/questions/472313/android-reverse-geocoding-getfromlocation

Comments

Popular posts from this blog

Tutorial Integration Firebase With Admob on Android

Firebase Configuration in Android

How To Generate A Random String Alphabet And Number in Java Android