无法找到我的设备
问题描述:
有与定位的问题...我使用的方法来获得纬度和经度。但我的Location变量为null。所以我的坐标是0,0。 有人可以帮我吗? 这里是代码:无法找到我的设备
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
checkGPS = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
checkNetwork = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!checkGPS && !checkNetwork) {
Toast.makeText(mContext, R.string.no_service, Toast.LENGTH_SHORT).show();
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (checkNetwork) {
try {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
loc = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
} catch (SecurityException e) {
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (checkGPS) {
if (loc == null) {
try {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
loc = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
}
} catch (SecurityException e) {
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return loc;
}
禄为空呢。当我编译应用程序时,我的手机上启用了GPS和WiFi。
答
鉴于您正在吞咽SecurityExceptions,我猜你的应用没有分别请求网络和GPS位置所需的permission至ACCESS_COARSE_LOCATION和ACCESS_FINE_LOCATION。
我一般建议不要默默吞咽异常。这些特殊的SecurityExceptions,你应该从来没有需要添加一个catch语句为他们(这是您的线索的东西是错误的),B/C,你应该已经在尝试访问该资源之前调用checkSelfPermission()。