这是我获取gps坐标的代码。
if (Build.VERSION.SDK_INT >= 23) {
getPermissions();
} else
doGPS();
private void getPermissions() {
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
if (!hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
} else
doGPS();
}
public static boolean hasPermissions(Context context, String... permissions) {
if (context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
@Override
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {
if (permsRequestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getPermissions();
}
}
public void doGPS() {
try {
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
getCordinate(location.getLatitude(),location.getLongitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
}
首先检查权限,当它授予权限时,请致电getGps
我的清单中有这个代码:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
永远都需要调用方法getCordinate
,它根本不会来onLocationChanged
。
我已经检查了谷歌地图等其他应用,它可以正确获取坐标。
更新1: 有一些奇怪的事情,当我在一个没有任何移动的地方时,它不起作用但是当我开始四处移动时,它起作用,我怎么能强迫它获得坐标而我不是搬家?