所以我做了这个代码,它是工作的,但位置只能得到检索,如果我打开谷歌地图之前启动应用程序,我想做的是让应用程序检测我的当前位置,而不是最后已知的位置。我发现有一个名为getCurrentLocation()的方法可以用来检索我的位置,但我不知道在参数中放什么。请帮帮我.这是我的密码
private void getLocation(){
//Check Permissions again
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(Reclamation.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(Reclamation.this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.INTERNET}, REQUEST_PERMISSION_LOCATION);
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location LocationGps = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location LocationNetwork = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location LocationPassive = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (LocationGps != null) {
double lat = LocationGps.getLatitude();
double longi = LocationGps.getLongitude();
latitude = String.valueOf(lat);
longitude = String.valueOf(longi);
} else if (LocationNetwork != null) {
double lat = LocationNetwork.getLatitude();
double longi = LocationNetwork.getLongitude();
latitude = String.valueOf(lat);
longitude = String.valueOf(longi);
} else if (LocationPassive != null) {
double lat = LocationPassive.getLatitude();
double longi = LocationPassive.getLongitude();
latitude = String.valueOf(lat);
longitude = String.valueOf(longi);
Toast.makeText(Reclamation.this, "Passive is not null :D", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Reclamation.this, "Can't Get Your Location", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(Reclamation.this, SetLocation.class);
intent.putExtra("latt", latitude);
intent.putExtra("lonn", longitude);
Toast.makeText(Reclamation.this, latitude + " " + longitude, Toast.LENGTH_SHORT).show();
startActivityForResult(intent, 3);
}
}
与
api 'com.google.android.gms:play-services-location:18.0.0'
您可以使用此方法
FusedLocationProviderClient fusedLocationClient;
FusedLocationProviderClient locationProviderClient = LocationServices.
getFusedLocationProviderClient(this);
//LOCATION AVAILABILITY
fusedLocationClient
.getLocationAvailability()
.addOnSuccessListener(new OnSuccessListener<LocationAvailability>() {
@Override
public void onSuccess(LocationAvailability locationAvailability) {
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
//LAST LOCATION
fusedLocationClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
//AND MORE...
fusedLocationClient
.requestLocationUpdates()
...