Android Location

AndroidManifest.xml

We need permission to get location.

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

To get location, we need these permissions. These are minimum settings.

Steps

We have 3 parts.

  • Prepare
  • Request
  • Listener

Code

public class MeasureFragment extends Fragment implements LocationListener {
    
    private LocationManager lmanager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Prepare
        lmanager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
        setLocationLoader();
    }

    public void setLocationLoader () {
        Criteria criteria = new Criteria();
        // Set Accuracy
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);

        // Power Requirement
        criteria.setPowerRequirement(Criteria.POWER_LOW);

        // Get Location Provider
        provider = lmanager.getBestProvider(criteria, true);
    }

    // LocationListener
    @Override
    public void onLocationChanged(Location location) {
        // You can get latitude, longitude from Location    
        //location.getLatitude(), location.getLongitude());
    }

    @Override
    public void onProviderDisabled(String provider) {
        
    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        
    }
}

Accuracy

You can set accuracy. The way to get location changes according to accuracy setting.

criteria.setAccuracy(Criteria.ACCURACY_COARSE);

Accuracy levels are Criteria.ACCURACY_FINE, Criteria.ACCURACY_HIGH, Criteria.ACCURACY_MEDIUM, Criteria.ACCURACY_LOW, Criteria.ACCURACY_COARSE

See Android Developer Criteria

Power

criteria.setPowerRequirement(Criteria.POWER_LOW);

Power levels are Criteria.POWER_HIGH, Criteria.POWER_MEDIUM, Criteria.POWER_LOW