Android get location

In this Android tip, I am going to shows you how to get the location of an Android device. To achieve this goal, first you have to obtain an instance of the LocationManager using getSystemService() method passing the Context.LOCATION_SERVICE value. From the LocationManager instance, you can list all enabled location providers using the getProviders() method. To get the Location object from a provider, you will use the getLastKnownLocation(). The Location object stores information about the latitude and longitude of the Android phone. When you get the latitude and longitude of the location, you can pass them to the Geocoder to retrieve the textual address of the location.
Now to have example application on getting location of an Android phone, create a new Android project. Then modify the AndroidManifest.xml file to add the two permissions below to use location service as shown below. Without these permissions, you application cannot retrieve the location correctly.

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Here is the code you have to write in the MainActivity class to get the latitude and longitude of location and display its textual address in a TextView. In your activity_main.xml file, you need a TextView widget that its id attribute has the value of txtview. Translating from latitude and longitude to a textual address might take time. So, it is a good idea to place this task in background using AsyncTask.


package com.example.androidexample;
import java.util.List;
import java.util.Locale;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
private LocationManager locationManager;
private Location mylocation;
private TextView tv;
    protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     tv=(TextView)findViewById(R.id.txtview);
      mylocation=getLocation();
     if(mylocation!=null)
     {
     if(Geocoder.isPresent()){
     AddressTask AT=new AddressTask();
     AT.execute(mylocation);
     }
     else
     Toast.makeText(this, "Geocoder not presented", Toast.LENGTH_SHORT).show();    
    
     }
     else
     Toast.makeText(this, "Unable to determine the location", Toast.LENGTH_SHORT).show();
  
}

public Location getLocation(){
//Create locationManager object from the Android system location service
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//retrieve the available location providers
   List<String> providers = locationManager.getProviders(true);
   for (String provider : providers) {
   //get the last known location from a provider
   mylocation= locationManager.getLastKnownLocation(provider);   
   }
   return mylocation;
  
}
private class AddressTask extends AsyncTask<Location, Void, Void> {

String addressText="Address: ";
protected Void doInBackground(Location... params) {
  Geocoder geocoder =new Geocoder(getBaseContext(), Locale.getDefault());  
  List<Address> addresses = null;
  Location location=params[0];
  try {    
  addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
  } catch (Exception e1) {Log.e(this.toString(),e1.getMessage());}

  if (addresses != null && addresses.size() > 0) {
  // Get the first address
  Address address = addresses.get(0);
  // Get street, city, and country
  addressText=address.getMaxAddressLineIndex()>0? address.getAddressLine(0) + ", ":"null, ";
  addressText+=address.getLocality()+", "+address.getCountryName();
    
  }
return null;
}
protected void onPostExecute(Void result) {
// Display the results of the lookup.
tv.setText(addressText);
}

}

}


Android-get-location

Posted by: Dara | post date: 10-08-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.