我正在编写一个使用GPS获取用户位置的应用。我添加了显示(android.permission.ACCESS_FINE_LOCATION)
的权限,询问了所需的运行时权限并使我的应用程序开始搜索,但此搜索可能需要很长时间(大约5分钟)或永远不会返回任何结果。但原始的Google地图应用程序会立即确定我的位置,因此问题不在GPS中。也许有人知道问题是什么?
这是我的代码:
public class MainActivity extends AppCompatActivity
implements ActivityCompat.OnRequestPermissionsResultCallback {
private static final int PERMISSION_REQUEST_GPS = 0;
LocationManager manager;
private LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (location != null) {
String lathitude = String.valueOf(location.getLatitude());
String longitude = String.valueOf(location.getLongitude());
Toast.makeText(getApplicationContext(),
"Your Location is - \nLat: " + lathitude + "\nLong: " + longitude,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Sorry, location unavailable",
Toast.LENGTH_LONG).show();
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btnShowLocation).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
findGPSLocation();
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_GPS) {
// Request for camera permission.
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission has been granted.
startGPSSearch();
} else {
// Permission request was denied.
}
}
}
private void findGPSLocation() {
// Check if the Camera permission has been granted
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
// Permission is already available
startGPSSearch();
} else {
// Permission is missing and must be requested.
requestPermission();
}
}
private void requestPermission() {
// Permission has not been granted and must be requested.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_REQUEST_GPS);
}
private void startGPSSearch() {
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
}
}
答案 0 :(得分:1)
您要求GPS位置,这意味着Android正在等待来自卫星的GPS修复。如果您在建筑物内测试代码,则可能无法实现,或者可能需要更长时间。谷歌地图(最有可能)使用融合位置api,它利用了许多不同的位置来源 - 但它提供了位置的准确性,因此如果符合您的需求,您可以自己思考(谷歌地图显示更大的适应性) /你的位置周围的小圆圈。)
要使用融合位置api,请从此处开始:https://developers.google.com/location-context/fused-location-provider/
您可以通过添加以下内容来请求网络位置更新:
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
见这里:https://developer.android.com/guide/topics/location/strategies