42.Android LocationManager

42.Android 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 獲取

LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

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 實例

this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, 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, 1000, 0, 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);
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章