天天看點

42.Android LocationManager42.Android LocationManager

42.Android LocationManager

  • Android LocationManager
    • LocationManager 介紹
    • LocationManager 擷取
    • LocationListener 初始化
    • LocationManager 添加監聽
    • LocationManager 取得所有Provider
    • LocationManager 比對合适Provider
    • LocationManager 測試代碼

LocationManager 介紹

LocationManager 提供了通路系統位置服務,這些服務允許應用程式能夠獲得定期更新裝置的地理位置。

由于 LocationManager 屬于一種系統服務類型,是以還是需要通過:

Context.getSystemService(Context.LOCATION_SERVICE)

于此同時,還要在AndroidManifest.xml裡配置如下權限:

  • 精确位置權限

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

  • 粗糙位置權限

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

LocationManager 擷取

LocationListener 初始化

LocationListener locationListener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        /**
         * 經度
         * 緯度
         * 海拔
         */
        Log.i(TAG, "Longitude:" + Double.toString(location.getLongitude()));
        Log.i(TAG, "Latitude:" + Double.toString(location.getLatitude()));
        Log.i(TAG, "getAltitude:" + Double.toString(location.getAltitude()));
    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
};
           

LocationManager 添加監聽

在LocationManager的源碼中有這段:

/**
     * Name of the network location provider.
     * <p>This provider determines location based on
     * availability of cell tower and WiFi access points. Results are retrieved
     * by means of a network lookup.
     */
    public static final String NETWORK_PROVIDER = "network";

    /**
     * Name of the GPS location provider.
     *
     * <p>This provider determines location using
     * satellites. Depending on conditions, this provider may take a while to return
     * a location fix. Requires the permission
     * {@link android.Manifest.permission#ACCESS_FINE_LOCATION}.
     *
     * <p> The extras Bundle for the GPS location provider can contain the
     * following key/value pairs:
     * <ul>
     * <li> satellites - the number of satellites used to derive the fix
     * </ul>
     */
    public static final String GPS_PROVIDER = "gps";

    /**
     * A special location provider for receiving locations without actually initiating
     * a location fix.
     *
     * <p>This provider can be used to passively receive location updates
     * when other applications or services request them without actually requesting
     * the locations yourself.  This provider will return locations generated by other
     * providers.  You can query the {@link Location#getProvider()} method to determine
     * the origin of the location update. Requires the permission
     * {@link android.Manifest.permission#ACCESS_FINE_LOCATION}, although if the GPS is
     * not enabled this provider might only return coarse fixes.
     */
    public static final String PASSIVE_PROVIDER = "passive";
           

有這三種Provider:

  • NETWORK_PROVIDER
  • GPS_PROVIDER
  • PASSIVE_PROVIDER

LocationManager.requestLocationUpdates

public void requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

provider:LocationManager的類型(上述的三種填寫一個)

minTime:兩次定位的最小時間間隔(最少多少秒更新一次)

minDistance:兩次定位的最小距離(最少走多遠就更新一次)

listener:LocationListener 執行個體

LocationManager 取得所有Provider

LocationManager.getAllProviders

public List<String> getAllProviders()

LocationManager 比對合适Provider

這裡要用到一個類 - Criteria。

/**
 * 擷取以下條件下,最合适的provider
 */
private void getBestProvider() {
    Criteria criteria = new Criteria();
    // 精度高
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    // 低消耗
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    // 海拔
    criteria.setAltitudeRequired(true);
    // 速度
    criteria.setSpeedRequired(true);
    // 費用
    criteria.setCostAllowed(false);
    String provider = locationManager.getBestProvider(criteria, false); //false是指不管目前擴充卡是否可用
    this.bestProviderTV.setText(provider);
}
           

LocationManager 測試代碼

LocationManagerActivity

public class LocationManagerActivity extends AppCompatActivity {

    private static final String TAG = "LocationManagerActivity";

    private LocationManager locationManager;

    private TextView longitudeTV;
    private TextView latitudeTV;
    private TextView altitudeTV;
    private TextView providersTV;
    private TextView bestProviderTV;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_location_manager);
        this.initViews();
        this.locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        LocationListener locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                /**
                 * 經度
                 * 緯度
                 * 海拔
                 */
                Log.i(TAG, "Longitude:" + Double.toString(location.getLongitude()));
                Log.i(TAG, "Latitude:" + Double.toString(location.getLatitude()));
                Log.i(TAG, "getAltitude:" + Double.toString(location.getAltitude()));
            }

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

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };
        this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, , , locationListener);
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        this.longitudeTV.setText(location.getLongitude() + "");
        this.latitudeTV.setText(location.getLatitude() + "");
        this.altitudeTV.setText(location.getAltitude() + "");

        this.getProviders();
        this.getBestProvider();
    }

    /**
     * 擷取全部的provider
     */
    private void getProviders() {
        String providers = "";
        for (String provider : this.locationManager.getAllProviders()) {
            providers += provider + " ";
        }
        this.providersTV.setText(providers);
    }

    /**
     * 擷取以下條件下,最合适的provider
     */
    private void getBestProvider() {
        Criteria criteria = new Criteria();
        // 精度高
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        // 低消耗
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        // 海拔
        criteria.setAltitudeRequired(true);
        // 速度
        criteria.setSpeedRequired(true);
        // 費用
        criteria.setCostAllowed(false);
        String provider = locationManager.getBestProvider(criteria, false); //false是指不管目前擴充卡是否可用
        this.bestProviderTV.setText(provider);
    }


    private void initViews() {
        this.longitudeTV = (TextView) this.findViewById(R.id.location_longitude_tv);
        this.latitudeTV = (TextView) this.findViewById(R.id.location_latitude_tv);
        this.altitudeTV = (TextView) this.findViewById(R.id.location_altitude_tv);
        this.providersTV = (TextView) this.findViewById(R.id.location_providers_tv);
        this.bestProviderTV = (TextView) this.findViewById(R.id.location_best_provider_tv);
    }

}