我需要在android中找到用户位置。由于我不想使用GPS,我尝试使用下面的代码来查找基于他/她的网络的用户位置,这适用于某些设备但不适用于所有设备,问题是什么?是因为Android版本还是硬件问题?
private double x, y;
private LocationManager lm;
lm = (LocationManager) getActivity().getSystemService(
Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
0, locationListenerNetwork);
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
x = location.getLatitude();
y = location.getLongitude();
lm.removeUpdates(this);
Geocoder gcd = new Geocoder(getActivity(), Locale.getDefault());
List<Address> addresses;
addresses = gcd.getFromLocation(x, y, 1);
city = addresses.get(0).getLocality();
}
答案 0 :(得分:0)
试试这个 在FetchLocationTask类中给出纬度和经度
latitude = 27.003434;
longitude = 23.458569;
new FetchLocationTask(getActivity(), latitude, longitude).execute();
public class FetchLocationTask extends AsyncTask<Void, Void, Void> {
public Context context;
// private ProgressDialog mProgressDialog;
public String addressUrl;
public BufferedReader in;
public FetchLocationTask(Context context, double lat, double longi) {
this.context = context;
addressUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + longi + "&sensor=true";
}
@Override
protected void onPreExecute() {
}
/**
* Call the webservice and parse the data from the service in
* background.
*/
@Override
protected Void doInBackground(Void... params) {
try {
HttpClient httpClient = new DefaultHttpClient();// Client
HttpGet getRequest = new HttpGet();
getRequest.setURI(new URI(addressUrl));
HttpResponse response = httpClient.execute(getRequest);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
JSONObject jsonObject = new JSONObject(page);
if (jsonObject.has("results")) {
JSONArray jsonArray = (JSONArray) jsonObject.get("results");
if (jsonArray.length() > 0) {
jsonObject = (JSONObject) jsonArray.get(0);
if (jsonObject.has("formatted_address")) {
address = (String) jsonObject.get("formatted_address");
}
}
return null;
}
return null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* onPostExecute method after called webService and Set the data into
* adapter after background task is complete.
*/
@Override
protected void onPostExecute(Void result) {
if (address != null && address.length() > 0) {
Log.i("map", "My:::" + address);
etx_address.setText(address.toString());
}
}
}