使用Android的gps定位时设置监听事件一定要在oncreate()方法中。之前在使用的时候我好像是在需要的时候才设置的定位监听,有问题,放到oncreate()方法里面才正常了。
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
setLocationListener();
如果没有打开gps定位就去打开设置页面进行打开
public void setLocationListener() {
LocationProvider gpsProvider = mLocationManager.getProvider(LocationManager.GPS_PROVIDER);//1.通过GPS定位,较精确,也比较耗电
// 通过GPS卫星定位,定位级别可以精确到街(通过24颗卫星定位,在室外和空旷的地方定位准确、速度快)
boolean gps = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (gps) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0, this);
}else {
//无法定位:1、提示用户打开定位服务;2、跳转到设置界面
Toast.makeText(this, "无法定位,请打开定位服务", Toast.LENGTH_LONG).show();
Intent i = new Intent();
i.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
return;
}
}
作者:danfengw 发表于2017/3/9 10:37:17 原文链接
阅读:152 评论:0 查看评论