rikisaraan

GetLocationFromGPS

Apr 13th, 2020
431
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.89 KB | None | 0 0
  1. //Android Manifest
  2. <uses-permission android:name="android.permission.INTERNET" />
  3. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  4.  
  5. //Activity
  6. import android.os.Bundle;
  7. import android.app.Activity;
  8. import android.view.Menu;
  9. import android.widget.TextView;
  10.  
  11. public class MainActivity extends Activity {
  12.  
  13.     TextView textview;
  14.  
  15.     @Override
  16.     protected void onCreate(Bundle savedInstanceState) {
  17.         super.onCreate(savedInstanceState);
  18.         setContentView(R.layout.geo_locations);
  19.  
  20.         // check if GPS enabled
  21.         GPSTracker gpsTracker = new GPSTracker(this);
  22.  
  23.         if (gpsTracker.getIsGPSTrackingEnabled())
  24.         {
  25.             String stringLatitude = String.valueOf(gpsTracker.latitude);
  26.             textview = (TextView)findViewById(R.id.fieldLatitude);
  27.             textview.setText(stringLatitude);
  28.  
  29.             String stringLongitude = String.valueOf(gpsTracker.longitude);
  30.             textview = (TextView)findViewById(R.id.fieldLongitude);
  31.             textview.setText(stringLongitude);
  32.  
  33.             String country = gpsTracker.getCountryName(this);
  34.             textview = (TextView)findViewById(R.id.fieldCountry);
  35.             textview.setText(country);
  36.  
  37.             String city = gpsTracker.getLocality(this);
  38.             textview = (TextView)findViewById(R.id.fieldCity);
  39.             textview.setText(city);
  40.  
  41.             String postalCode = gpsTracker.getPostalCode(this);
  42.             textview = (TextView)findViewById(R.id.fieldPostalCode);
  43.             textview.setText(postalCode);
  44.  
  45.             String addressLine = gpsTracker.getAddressLine(this);
  46.             textview = (TextView)findViewById(R.id.fieldAddressLine);
  47.             textview.setText(addressLine);
  48.         }
  49.         else
  50.         {
  51.             // can't get location
  52.             // GPS or Network is not enabled
  53.             // Ask user to enable GPS/network in settings
  54.             gpsTracker.showSettingsAlert();
  55.         }
  56.     }
  57.  
  58.     @Override
  59.     public boolean onCreateOptionsMenu(Menu menu) {
  60.         // Inflate the menu; this adds items to the action bar if it is present.
  61.         getMenuInflater().inflate(R.menu.varna_lab_geo_locations, menu);
  62.         return true;
  63.     }
  64. }
  65.  
  66.  
  67.  
  68.  
  69.  
  70. //GPS Tracker
  71. import java.io.IOException;
  72. import java.util.List;
  73. import java.util.Locale;
  74.  
  75. import android.app.AlertDialog;
  76. import android.app.Service;
  77. import android.content.Context;
  78. import android.content.DialogInterface;
  79. import android.content.Intent;
  80. import android.location.Address;
  81. import android.location.Geocoder;
  82. import android.location.Location;
  83. import android.location.LocationListener;
  84. import android.location.LocationManager;
  85. import android.os.Bundle;
  86. import android.os.IBinder;
  87. import android.provider.Settings;
  88. import android.util.Log;
  89.  
  90. /**
  91.  * Create this Class from tutorial :
  92.  * http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial
  93.  *
  94.  * For Geocoder read this : http://stackoverflow.com/questions/472313/android-reverse-geocoding-getfromlocation
  95.  *
  96.  */
  97.  
  98. public class GPSTracker extends Service implements LocationListener {
  99.  
  100.     // Get Class Name
  101.     private static String TAG = GPSTracker.class.getName();
  102.  
  103.     private final Context mContext;
  104.  
  105.     // flag for GPS Status
  106.     boolean isGPSEnabled = false;
  107.  
  108.     // flag for network status
  109.     boolean isNetworkEnabled = false;
  110.  
  111.     // flag for GPS Tracking is enabled
  112.     boolean isGPSTrackingEnabled = false;
  113.  
  114.     Location location;
  115.     double latitude;
  116.     double longitude;
  117.  
  118.     // How many Geocoder should return our GPSTracker
  119.     int geocoderMaxResults = 1;
  120.  
  121.     // The minimum distance to change updates in meters
  122.     private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
  123.  
  124.     // The minimum time between updates in milliseconds
  125.     private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
  126.  
  127.     // Declaring a Location Manager
  128.     protected LocationManager locationManager;
  129.  
  130.     // Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
  131.     private String provider_info;
  132.  
  133.     public GPSTracker(Context context) {
  134.         this.mContext = context;
  135.         getLocation();
  136.     }
  137.  
  138.     /**
  139.      * Try to get my current location by GPS or Network Provider
  140.      */
  141.     public void getLocation() {
  142.  
  143.         try {
  144.             locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
  145.  
  146.             //getting GPS status
  147.             isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
  148.  
  149.             //getting network status
  150.             isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
  151.  
  152.             // Try to get location if you GPS Service is enabled
  153.             if (isGPSEnabled) {
  154.                 this.isGPSTrackingEnabled = true;
  155.  
  156.                 Log.d(TAG, "Application use GPS Service");
  157.  
  158.                 /*
  159.                  * This provider determines location using
  160.                  * satellites. Depending on conditions, this provider may take a while to return
  161.                  * a location fix.
  162.                  */
  163.  
  164.                 provider_info = LocationManager.GPS_PROVIDER;
  165.  
  166.             } else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled
  167.                 this.isGPSTrackingEnabled = true;
  168.  
  169.                 Log.d(TAG, "Application use Network State to get GPS coordinates");
  170.  
  171.                 /*
  172.                  * This provider determines location based on
  173.                  * availability of cell tower and WiFi access points. Results are retrieved
  174.                  * by means of a network lookup.
  175.                  */
  176.                 provider_info = LocationManager.NETWORK_PROVIDER;
  177.  
  178.             }
  179.  
  180.             // Application can use GPS or Network Provider
  181.             if (!provider_info.isEmpty()) {
  182.                 locationManager.requestLocationUpdates(
  183.                     provider_info,
  184.                     MIN_TIME_BW_UPDATES,
  185.                     MIN_DISTANCE_CHANGE_FOR_UPDATES,
  186.                     this
  187.                 );
  188.  
  189.                 if (locationManager != null) {
  190.                     location = locationManager.getLastKnownLocation(provider_info);
  191.                     updateGPSCoordinates();
  192.                 }
  193.             }
  194.         }
  195.         catch (Exception e)
  196.         {
  197.             //e.printStackTrace();
  198.             Log.e(TAG, "Impossible to connect to LocationManager", e);
  199.         }
  200.     }
  201.  
  202.     /**
  203.      * Update GPSTracker latitude and longitude
  204.      */
  205.     public void updateGPSCoordinates() {
  206.         if (location != null) {
  207.             latitude = location.getLatitude();
  208.             longitude = location.getLongitude();
  209.         }
  210.     }
  211.  
  212.     /**
  213.      * GPSTracker latitude getter and setter
  214.      * @return latitude
  215.      */
  216.     public double getLatitude() {
  217.         if (location != null) {
  218.             latitude = location.getLatitude();
  219.         }
  220.  
  221.         return latitude;
  222.     }
  223.  
  224.     /**
  225.      * GPSTracker longitude getter and setter
  226.      * @return
  227.      */
  228.     public double getLongitude() {
  229.         if (location != null) {
  230.             longitude = location.getLongitude();
  231.         }
  232.  
  233.         return longitude;
  234.     }
  235.  
  236.     /**
  237.      * GPSTracker isGPSTrackingEnabled getter.
  238.      * Check GPS/wifi is enabled
  239.      */
  240.     public boolean getIsGPSTrackingEnabled() {
  241.  
  242.         return this.isGPSTrackingEnabled;
  243.     }
  244.  
  245.     /**
  246.      * Stop using GPS listener
  247.      * Calling this method will stop using GPS in your app
  248.      */
  249.     public void stopUsingGPS() {
  250.         if (locationManager != null) {
  251.             locationManager.removeUpdates(GPSTracker.this);
  252.         }
  253.     }
  254.  
  255.     /**
  256.      * Function to show settings alert dialog
  257.      */
  258.     public void showSettingsAlert() {
  259.         AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
  260.  
  261.         //Setting Dialog Title
  262.         alertDialog.setTitle(R.string.GPSAlertDialogTitle);
  263.  
  264.         //Setting Dialog Message
  265.         alertDialog.setMessage(R.string.GPSAlertDialogMessage);
  266.  
  267.         //On Pressing Setting button
  268.         alertDialog.setPositiveButton(R.string.action_settings, new DialogInterface.OnClickListener() {
  269.  
  270.             @Override
  271.             public void onClick(DialogInterface dialog, int which)
  272.             {
  273.                 Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
  274.                 mContext.startActivity(intent);
  275.             }
  276.         });
  277.  
  278.         //On pressing cancel button
  279.         alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
  280.  
  281.             @Override
  282.             public void onClick(DialogInterface dialog, int which)
  283.             {
  284.                 dialog.cancel();
  285.             }
  286.         });
  287.  
  288.         alertDialog.show();
  289.     }
  290.  
  291.     /**
  292.      * Get list of address by latitude and longitude
  293.      * @return null or List<Address>
  294.      */
  295.     public List<Address> getGeocoderAddress(Context context) {
  296.         if (location != null) {
  297.  
  298.             Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
  299.  
  300.             try {
  301.                 /**
  302.                  * Geocoder.getFromLocation - Returns an array of Addresses
  303.                  * that are known to describe the area immediately surrounding the given latitude and longitude.
  304.                  */
  305.                 List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);
  306.  
  307.                 return addresses;
  308.             } catch (IOException e) {
  309.                 //e.printStackTrace();
  310.                 Log.e(TAG, "Impossible to connect to Geocoder", e);
  311.             }
  312.         }
  313.  
  314.         return null;
  315.     }
  316.  
  317.     /**
  318.      * Try to get AddressLine
  319.      * @return null or addressLine
  320.      */
  321.     public String getAddressLine(Context context) {
  322.         List<Address> addresses = getGeocoderAddress(context);
  323.  
  324.         if (addresses != null && addresses.size() > 0) {
  325.             Address address = addresses.get(0);
  326.             String addressLine = address.getAddressLine(0);
  327.  
  328.             return addressLine;
  329.         } else {
  330.             return null;
  331.         }
  332.     }
  333.  
  334.     /**
  335.      * Try to get Locality
  336.      * @return null or locality
  337.      */
  338.     public String getLocality(Context context) {
  339.         List<Address> addresses = getGeocoderAddress(context);
  340.  
  341.         if (addresses != null && addresses.size() > 0) {
  342.             Address address = addresses.get(0);
  343.             String locality = address.getLocality();
  344.  
  345.             return locality;
  346.         }
  347.         else {
  348.             return null;
  349.         }
  350.     }
  351.  
  352.     /**
  353.      * Try to get Postal Code
  354.      * @return null or postalCode
  355.      */
  356.     public String getPostalCode(Context context) {
  357.         List<Address> addresses = getGeocoderAddress(context);
  358.  
  359.         if (addresses != null && addresses.size() > 0) {
  360.             Address address = addresses.get(0);
  361.             String postalCode = address.getPostalCode();
  362.  
  363.             return postalCode;
  364.         } else {
  365.             return null;
  366.         }
  367.     }
  368.  
  369.     /**
  370.      * Try to get CountryName
  371.      * @return null or postalCode
  372.      */
  373.     public String getCountryName(Context context) {
  374.         List<Address> addresses = getGeocoderAddress(context);
  375.         if (addresses != null && addresses.size() > 0) {
  376.             Address address = addresses.get(0);
  377.             String countryName = address.getCountryName();
  378.  
  379.             return countryName;
  380.         } else {
  381.             return null;
  382.         }
  383.     }
  384.  
  385.     @Override
  386.     public void onLocationChanged(Location location) {
  387.     }
  388.  
  389.     @Override
  390.     public void onStatusChanged(String provider, int status, Bundle extras) {
  391.     }
  392.  
  393.     @Override
  394.     public void onProviderEnabled(String provider) {
  395.     }
  396.  
  397.     @Override
  398.     public void onProviderDisabled(String provider) {
  399.     }
  400.  
  401.     @Override
  402.     public IBinder onBind(Intent intent) {
  403.         return null;
  404.     }
  405. }
Advertisement
Add Comment
Please, Sign In to add comment