Android GPS Location Manager Tutorial
if you are making any location-based application you can follow this tutorial to get Location automatically from LocationTracker.java class.
In this tutorial, I will show you how to get current Location and get an address from latitude and longitude.In this we have
- MainActivity as Activity to get Location on performing Click
- LocationTracker class to get Location
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidruler.mymap" > <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/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>
//layout for MainActivity.java
activity_main.xml
<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Button android:id="@+id/getlocation" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="getLocation" android:layout_above="@+id/location"/> <TextView android:id="@+id/location" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"/> <TextView android:id="@+id/address" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/location"/> </RelativeLayout>
MainActivity.java
package com.androidruler.mymap; import android.app.Activity; import android.content.Context; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationManager; import android.support.v4.app.FragmentActivity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import java.util.List; import java.util.Locale; public class MainActivity extends Activity { TextView address,location; Button getLocation; LocationTracker tracker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); address=(TextView)findViewById(R.id.address); location=(TextView)findViewById(R.id.location); getLocation=(Button)findViewById(R.id.getlocation); getLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //create LocationTracker Object tracker=new LocationTracker(MainActivity.this); // check if location is available if(tracker.isLocationEnabled) { double latitude=tracker.getLatitude(); double longitude=tracker.getLongitude(); location.setText("Your Location is Latitude= " + latitude + " Longitude= " + longitude); String addres= getCompleteAddressString(latitude,longitude); address.setText(addres); } else { // show dialog box to user to enable location tracker.askToOnLocation(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private String getCompleteAddressString(double LATITUDE, double LONGITUDE) { String strAdd = ""; Geocoder geocoder = new Geocoder(this, Locale.getDefault()); try { List<Address> addresses = geocoder .getFromLocation(LATITUDE, LONGITUDE, 1); if (addresses != null) { android.location.Address returnedAddress = addresses.get(0); StringBuilder strReturnedAddress = new StringBuilder(""); for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) { strReturnedAddress .append(returnedAddress.getAddressLine(i)).append( "n"); } strAdd = strReturnedAddress.toString(); Log.w(" location address", ""+ strReturnedAddress.toString()); } else { Log.w(" location address", "No Address returned!"); } } catch (Exception e) { e.printStackTrace(); Log.w(" location address", "Cannot get Address!"); } return strAdd; } }
//location tracker to get current location updates periodically
LocationTracker.java
package com.androidruler.mymap; import android.app.AlertDialog; import android.app.Service; 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.os.IBinder; import android.provider.Settings; import android.support.annotation.Nullable; import android.widget.Toast; /** * Created by androidruler on 24/02/16. */ public class LocationTracker extends Service implements LocationListener { //declaring Context variable private final Context con; //flag for gps boolean isGPSOn=false; //flag for network location boolean isNetWorkEnabled=false; //flag to getlocation boolean isLocationEnabled=false; //minimum distance to request for location update private static final long MIN_DISTANCE_TO_REQUEST_LOCATION=1; // in meters // minimum time to request location updates private static final long MIN_TIME_FOR_UPDATES=1000*1; // 1 sec //location Location location; //latitude and longitude double latitude,longitude; //Declaring a LocationManager LocationManager locationManager; public LocationTracker(Context context) { this.con=context; checkIfLocationAvailable(); } public Location checkIfLocationAvailable() { try { locationManager=(LocationManager)con.getSystemService(LOCATION_SERVICE); //check for gps availability isGPSOn=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); //check for network availablity isNetWorkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); if(!isGPSOn && !isNetWorkEnabled) { isLocationEnabled=false; // no location provider is available show toast to user Toast.makeText(con,"No Location Provider is Available",Toast.LENGTH_SHORT).show(); } else { isLocationEnabled=true; // if network location is available request location update if(isNetWorkEnabled) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_FOR_UPDATES,MIN_DISTANCE_TO_REQUEST_LOCATION,this); if(locationManager!=null) { location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if(location!=null) { latitude=location.getLatitude(); longitude=location.getLongitude(); } } } if(isGPSOn) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_FOR_UPDATES,MIN_DISTANCE_TO_REQUEST_LOCATION,this); if(locationManager!=null) { location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if(location!=null) { latitude=location.getLatitude(); longitude=location.getLongitude(); } } } } }catch (Exception e) { } return location; } // call this to stop using location public void stopUsingLocation() { if(locationManager!=null) { locationManager.removeUpdates(LocationTracker.this); } } // call this to getLatitude public double getLatitude() { if(location!=null) { latitude=location.getLatitude(); } return latitude; } //call this to getLongitude public double getLongitude() { if(location!=null) { longitude=location.getLongitude(); } return longitude; } public boolean isLocationEnabled() { return this.isLocationEnabled; } //call to open settings and ask to enable Location public void askToOnLocation() { AlertDialog.Builder dialog=new AlertDialog.Builder(con); //set title dialog.setTitle("Settings"); //set Message dialog.setMessage("Location is not Enabled.Do you want to go to settings to enable it?"); // on pressing this will be called dialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); con.startActivity(intent); } }); //on Pressing cancel dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); // show Dialog box dialog.show(); } @Override public void onLocationChanged(Location location) { this.location=location; } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Nullable @Override public IBinder onBind(Intent intent) { return null; } }