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);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
com.miui.frameworks.servicestests (1 Test) [1/1] com.android.server.location.gnss.hal.Gpo4ClientTest#init: FAILED (141ms) STACKTRACE: java.lang.SecurityException: uid 10289 does not have android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION. at android.os.Parcel.createExceptionOrNull(Parcel.java:3011) at android.os.Parcel.createException(Parcel.java:2995) at android.os.Parcel.readException(Parcel.java:2978) at android.os.Parcel.readException(Parcel.java:2920) at android.location.ILocationManager$Stub$Proxy.registerLocationListener(ILocationManager.java:1291) at android.location.LocationManager.requestLocationUpdates(LocationManager.java:1551) at android.location.LocationManager.requestLocationUpdates(LocationManager.java:1234) at android.location.LocationManager.requestLocationUpdates(LocationManager.java:1199) at com.android.server.location.gnss.hal.Gpo4Client.registerPassiveLocationUpdates(Gpo4Client.java:198) at com.android.server.location.gnss.hal.Gpo4Client.init(Gpo4Client.java:78) at com.android.server.location.gnss.hal.Gpo4ClientTest.init(Gpo4ClientTest.java:209) ... 8 trimmed Caused by: android.os.RemoteException: Remote stack trace: at com.android.server.location.LocationPermissions.enforceLocationPermission(LocationPermissions.java:116) at com.android.server.location.LocationManagerService.registerLocationListener(LocationManagerService.java:786) at android.location.ILocationManager$Stub.onTransact(ILocationManager.java:582) at android.os.Binder.execTransactInternal(Binder.java:1285) at android.os.Binder.execTransact(Binder.java:1249)
最新发布
06-01

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值