我正在尝试通过我的Android应用程序中的GPS / Cellular获取位置(Lat,Long,Address)。这是下面的代码:
private class LocAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Obtaining location...Please Wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
@Override
protected String doInBackground(String... params) {
LocationDSR locationDSR=new LocationDSR(getActivity());
locationDSR.getListAddressFromGeocoder();
return null;
}
@Override
protected void onPostExecute(String result) {
System.out.println("Location obtained");
dialog.hide();
}
}
这里是locationDSR java:
public class LocationDSR implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
Context c;
GoogleApiClient mGoogleApiClient;
Location currentLocation;
SharedPreference sharedPreference;
ProgressDialog dialog;
public LocationDSR(Context c) {
this.c = c;
ApiClient();
mGoogleApiClient.connect();
}
synchronized void ApiClient() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(c)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
@Override
public void onLocationChanged(Location location) {
currentLocation = location;
System.out.println("onLocation changed :"+currentLocation);
}
@Override
public void onConnected(@Nullable Bundle bundle) {
try {
LocationRequest locationRequest = LocationRequest.create()
.setInterval(10 * 1000) // every 10 minutes
.setExpirationDuration(10 * 1000) // After 10 seconds
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, locationRequest, this);
} catch (SecurityException e) {
e.printStackTrace();
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
public void getListAddressFromGeocoder() {
new AddressAsync().execute();
System.out.println("Inside getListAddressFromGeocoder");
}
class AddressAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... params) {
List<Address> addresses = null;
sharedPreference = new SharedPreference(c);
System.out.println("Inside doInBackground");
System.out.println("Current location : " + currentLocation);
if (currentLocation == null) {
LocationManager mlocManager = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE);
System.out.println("Current location null block");
try {
if (ActivityCompat.checkSelfPermission(c, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(c, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
currentLocation = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
System.out.println("Obtraining from GPS");
System.out.println("GPSlocation : "+currentLocation);
// Check both providers even for lastKnownLocation
if (currentLocation == null) {
currentLocation = mlocManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
System.out.println("Obtaining from network provider");
}
} catch (Exception e) {
System.out.println("Insiode catch block for current location not obtained");
e.printStackTrace();
}
}
if (currentLocation != null) {
String complete_address;
final double latitude = currentLocation.getLatitude();
final double longitude = currentLocation.getLongitude();
System.out.println("LATITUDE: " + currentLocation.getLatitude());
System.out.println("LONGITUDE: " + currentLocation.getLongitude());
sharedPreference.saveLatLogAddressPref(String.valueOf(latitude), String.valueOf(latitude), "Not available", true);
//Storing the latitude and longitude in sharedPreference (To be used in case address is not obtained or geocoder timesout)
ConnectionDetector cd = new ConnectionDetector(c);
if (cd.isInternetOn()) {
System.out.println("Internet on detected");
Geocoder geocoder = new Geocoder(c);
try {
System.out.println("Latitude for address : "+latitude);
System.out.println("Longitude for address : "+longitude);
addresses = geocoder.getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
Address addr = null;
if (addresses != null && addresses.size() > 0) {
addr = addresses.get(0);
String info = "Address is: ";
info += addr.getMaxAddressLineIndex() > 0 ? addr
.getAddressLine(0) : "";
info = info + ", " + addr.getLocality() + ", "
+ addr.getCountryName();
System.out.println("INFO : "+info);
} else
System.out.println("Address not found");
if (addresses != null || addresses.size() > 0) {
System.out.println("Addresses : "+addresses);
for (Address address : addresses) {
complete_address = String.valueOf(address.getAddressLine(0) + " " + address.getAddressLine(1) + " " + address.getAddressLine(2));
System.out.println("Complete address : "+complete_address);
if (complete_address.equals(" null null"))
{
complete_address = String.valueOf(address.getAdminArea()+" "+address.getLocality());
sharedPreference.saveLatLogAddressPref(String.valueOf(latitude), String.valueOf(latitude), complete_address, true);
}
else
{
sharedPreference.saveLatLogAddressPref(String.valueOf(latitude), String.valueOf(latitude), complete_address, true);
}
}
}
} catch (IOException e) {
System.out.println("Inside catch for geocoder");
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
}
}
}
然后弹出加载屏幕显示&#34;获取位置......请等待......&#34;但只有2秒钟。在这段时间内,只获得纬度和经度,而不是地址。地址查询addresses = geocoder.getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
完成需要大约2-3秒(我可以在logcat中看到它)。我也无法理解如何保持地址查询的加载屏幕。
此外,有时在通过gecoder查询地址时,会显示
java.io.IOException:等待服务器响应
超时
感谢任何帮助。