Recipe 8.2 Choosing the Best Location Provider to Use
You want to be able to choose the best provider possible to help you determine your location.
Solution
In the previous recipe, you saw how to use the GPS_PROVIDER and the NETWORK_PROVIDER to obtain your current location information using the various techniques (GPS, Wi-Fi, or cellular triangulation). However, sometimes you might want to let the OS determine which provider is best depending on your specific requirements. In this case, you can use the getBestProvider() method of the LocationManager class to help the application decide based on the specified criteria.
First, create an object of type LocationManager:
package net.learn2develop.locationproviders;
import android.app.Activity;
import android.location.LocationManager;
import android.os.Bundle;
public class MainActivity extends Activity {
LocationManager lm;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Instantiate the LocationManager class by calling the getSystemService() method:
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lm ...
Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.