//The code in my project:
private void GetLocation(){
// NETWORK
if (null == location && WeiboApplication.isNetworkAvailable(pContext)) {
location = getLocationWifi(pContext);
}
// Cell
if (null == location && WeiboApplication.isNetworkAvailable(pContext)) {
location = getLocationStation(pContext);
/*WifiInfoManager wm=new WifiInfoManager();
CellIdInfoManager cellID=new CellIdInfoManager();
location=callGear(wm.getWifiInfo(pContext), cellID.getCellIDInfo(pContext));*/
}
// GPS
if (WeiboApplication.isGpsAvailable(pContext)) {
location = getLocationGPS(pContext);
}
}
/**
* GetAddressByLocaion *
* @param location
* @return
*/
public static void doLocationName(Location location, Context pContext) {
if (null != location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
List<Address> addList = null;
addList = getLocationGoogleAPI(lat, lng, 1);
if (null == addList || addList.size() == 0) {
addList = getLocationGeocoderAPI(lat, lng, 1, pContext);
}
if (addList != null && addList.size() > 0) {
for (int i = 0; i < addList.size(); i++) {
Address ad = addList.get(i);
locationName = ad.getLocality();
if (ad.getThoroughfare() != null) {
locationName = locationName + ad.getThoroughfare();
}
}
}
} else {
locationName = "";
}
}
private static List<Address> getLocationGeocoderAPI(double lat, double lon, int maxResults, Context pContext) {
List<Address> results = new ArrayList<Address>();
try {
Geocoder ge = new Geocoder(pContext, Locale.getDefault());
results = ge.getFromLocation(lat, lon, 1);
} catch (IOException e) {
e.printStackTrace();
}
return results;
}
/**
* GetAddress ByLocation(Http)
*
* @param lat
* @param lon
* @param maxResults
* @return
*/
private static List<Address> getLocationGoogleAPI(double lat, double lon, int maxResults) {
String urlStr = "http://maps.google.com/maps/geo?q=" + lat + "," + lon + "&output=json&sensor=true";
String response = "";
List<Address> results = new ArrayList<Address>();
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 2000);
HttpConnectionParams.setSoTimeout(httpParams, 2000);
HttpClient client = new DefaultHttpClient(httpParams);
try {
HttpResponse hr = client.execute(new HttpGet(urlStr));
HttpEntity entity = hr.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
String buff = null;
while ((buff = br.readLine()) != null)
response += buff;
} catch (IOException e) {
e.printStackTrace();
}
JSONArray responseArray = null;
try {
JSONObject jsonObject = new JSONObject(response);
responseArray = jsonObject.getJSONArray("Placemark");
} catch (JSONException e) {
return results;
}
for (int i = 0; i < responseArray.length() && i < maxResults; i++) {
Address addy = new Address(Locale.getDefault());
try {
JSONObject jsl = responseArray.getJSONObject(i);
jsl = jsl.getJSONObject("AddressDetails").getJSONObject("Country").getJSONObject("AdministrativeArea")
.getJSONObject("Locality");
String locality = null;
if (jsl.getString("LocalityName") == null) {
locality = null;
} else {
locality = jsl.getString("LocalityName");
}
if (jsl.getJSONObject("DependentLocality").getString("DependentLocalityName") != null) {
locality = locality + jsl.getJSONObject("DependentLocality").getString("DependentLocalityName");
;
}
addy.setLocality(locality);
addy.setThoroughfare(jsl.getJSONObject("DependentLocality").getJSONObject("Thoroughfare")
.getString("ThoroughfareName"));
} catch (JSONException e) {
e.printStackTrace();
results.add(addy);
continue;
}
results.add(addy);
}
return results;
}
/**
* GetLocaionbyGPS
*
* @return
*/
private static Location getLocationGPS(Context pContext) {
LocationManager locationManager = (LocationManager) pContext.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String locationProvider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(locationProvider);
// location=locationManager.requestLocationUpdates(locationProvider,
// 30000, 10,new GpsLocationListener());
return location;
}
/**
* GetLocaionByWifi
*
* @param context
* @return
*/
private static Location getLocationWifi(Context pContext) {
Location location = null;
try {
LocationManager locationManager = (LocationManager) pContext.getSystemService(Context.LOCATION_SERVICE);
WifiManager wifiManager = (WifiManager) pContext.getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
System.out.println("------------location INFO:" + location);
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* getLocaionByCell
*
* @param context
* @return
*/
private static Location getLocationStation(Context pContext) {
TelephonyManager tm = (TelephonyManager) pContext.getSystemService(Context.TELEPHONY_SERVICE);
try {
if ((String) getNetType(pContext) != "UNKNOWN"&& ((String) getNetType(pContext) == "HSDPA" || getNetType(pContext) == "HSPA")) {// 3G
location = null;
GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation();
if (gcl == null) {
return null;
}
int cid = gcl.getCid();
int lac = gcl.getLac();
int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0, 3));
int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3, 5));
try {
// JSON
JSONObject holder = new JSONObject();
holder.put("version", "1.1.0");
holder.put("host", "maps.google.com");
holder.put("address_language", "zh_CN");
holder.put("request_address", true);
JSONArray array = new JSONArray();
JSONObject data = new JSONObject();
data.put("cell_id", cid); // 25070
data.put("location_area_code", lac);// 4474
data.put("mobile_country_code", mcc);// 460
data.put("mobile_network_code", mnc);// 0
data.put("radio_type","gsm");
array.put(data);
holder.put("cell_towers", array);
// hTTP
DefaultHttpClient client = new DefaultHttpClient();
String host=Proxy.getDefaultHost();
HttpPost post = new HttpPost("http://www.google.com/loc/json");
if (host!=null) {
int port = Proxy.getDefaultPort();
HttpHost httpHost=new HttpHost(host, port);
client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, httpHost);
}
StringEntity se = new StringEntity(holder.toString());
post.setEntity(se);
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
InputStream is = entity.getContent();
if (is == null) {
return null;
}
String jsonStr = JSONProvider.convertStreamToString(is);
if (jsonStr == null) {
return null;
}
JSONObject jsonObject = new JSONObject(jsonStr);
JSONObject jsonLocation = jsonObject.getJSONObject("location");
if (jsonLocation != null) {
String latitude = jsonLocation.getString("latitude");
String longitude = jsonLocation.getString("longitude");
location = new Location(AppLocation.class.getName());
location.setLatitude(Double.parseDouble(latitude));
location.setLongitude(Double.parseDouble(longitude));
}
} catch (Exception e) {
e.printStackTrace();
}
}
if ((String) getNetType(pContext) != "UNKNOWN" && (String) getNetType(pContext) == "UTMS") {
location_cdma = null;
location = null;
location_cdma = (CdmaCellLocation) tm.getCellLocation();// cdma
if (location_cdma != null) {
try {
int sid = location_cdma.getSystemId();
// mobileNetworkCode
int bid = location_cdma.getBaseStationId();
// cellId
int nid = location_cdma.getNetworkId();
// locationAreaCode
double CdmaLat = (double) location_cdma.getBaseStationLatitude() / 14400;
double CdmaLon = (double) location_cdma.getBaseStationLongitude() / 14400;
// json JSONObject holder = new JSONObject();
holder.put("version", "1.1.0");
holder.put("host", "maps.google.com");
holder.put("address_language", "zh_CN");
holder.put("radio_type", "cdma");
holder.put("request_address", true);
JSONArray array = new JSONArray();
JSONObject data = new JSONObject();
data.put("cell_id", bid); // 25070
data.put("location_area_code", nid);// 4474
data.put("mobile_country_code", 460);// 460
data.put("mobile_network_code", sid);// 0
array.put(data);
holder.put("cell_towers", array);
// http
DefaultHttpClient client = new DefaultHttpClient();
String host=Proxy.getDefaultHost();
HttpPost post = new HttpPost("http://www.google.com/loc/json");
if (host!=null) {
int port = Proxy.getDefaultPort();
HttpHost httpHost=new HttpHost(host, port);
client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, httpHost);
}
StringEntity se = new StringEntity(holder.toString());
post.setEntity(se);
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
InputStream is = entity.getContent();
if (is == null) {
return null;
}
String jsonStr = JSONProvider.convertStreamToString(is);
if (jsonStr == null) {
return null;
}
JSONObject jsonObject = new JSONObject(jsonStr);
JSONObject jsonLocation = jsonObject.getJSONObject("location");
if (jsonLocation != null) {
String latitude = jsonLocation.getString("latitude");
String longitude = jsonLocation.getString("longitude");
location = new Location(AppLocation.class.getName());
location.setLatitude(Double.parseDouble(latitude));
location.setLongitude(Double.parseDouble(longitude));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
if ((String) getNetType(pContext) != "UNKNOWN" && (String) getNetType(pContext) == "GPRS") {
location = null;
GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation();
int cid = gcl.getCid();
int lac = gcl.getLac();
int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0, 3));
int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3, 5));
try {
// JSON
JSONObject holder = new JSONObject();
holder.put("version", "1.1.0");
holder.put("host", "maps.google.com");
holder.put("address_language", "zh_CN");
holder.put("request_address", true);
JSONArray array = new JSONArray();
JSONObject data = new JSONObject();
data.put("cell_id", cid); // 25070
data.put("location_area_code", lac);// 4474
data.put("mobile_country_code", mcc);// 460
data.put("mobile_network_code", mnc);// 0
array.put(data);
holder.put("cell_towers", array);
DefaultHttpClient client = new DefaultHttpClient();
String host=Proxy.getDefaultHost();
HttpPost post = new HttpPost("http://www.google.com/loc/json");
if (host!=null) {
int port = Proxy.getDefaultPort();
HttpHost httpHost=new HttpHost(host, port);
client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, httpHost);
}
StringEntity se = new StringEntity(holder.toString());
post.setEntity(se);
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
InputStream is = entity.getContent();
if (is == null) {
return null;
}
String jsonStr = JSONProvider.convertStreamToString(is);
if (jsonStr == null) {
return null;
}
JSONObject jsonObject = new JSONObject(jsonStr);
JSONObject jsonLocation = jsonObject.getJSONObject("location");
if (jsonLocation != null) {
String latitude = jsonLocation.getString("latitude");
String longitude = jsonLocation.getString("longitude");
location = new Location(AppLocation.class.getName());
location.setLatitude(Double.parseDouble(latitude));
location.setLongitude(Double.parseDouble(longitude));
}
} catch (Exception e) {
e.printStackTrace();
}
}
if ((String) getNetType(pContext) != "UNKNOWN" && (String) getNetType(pContext) == "EDGE") {
location = null;
GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation();
int cid = gcl.getCid();
int lac = gcl.getLac();
int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0, 3));
int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3, 5));
try {
// Build json string which is used to search something
JSONObject holder = new JSONObject();
holder.put("version", "1.1.0");
holder.put("host", "maps.google.com");
holder.put("address_language", "zh_CN");
holder.put("request_address", true);
JSONArray array = new JSONArray();
JSONObject data = new JSONObject();
data.put("cell_id", cid); // 25070
data.put("location_area_code", lac);// 4474
data.put("mobile_country_code", mcc);// 460
data.put("mobile_network_code", mnc);// 0
array.put(data);
holder.put("cell_towers", array);
// create connection, send request then receive response
DefaultHttpClient client = new DefaultHttpClient();
String host=Proxy.getDefaultHost();
HttpPost post = new HttpPost("http://www.google.com/loc/json");
if (host!=null) {
int port = Proxy.getDefaultPort();
HttpHost httpHost=new HttpHost(host, port);
client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, httpHost);
}
StringEntity se = new StringEntity(holder.toString());
post.setEntity(se);
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
InputStream is = entity.getContent();
if (is == null) {
return null;
}
String jsonStr = JSONProvider.convertStreamToString(is);
if (jsonStr == null) {
return null;
}
JSONObject jsonObject = new JSONObject(jsonStr);
JSONObject jsonLocation = jsonObject.getJSONObject("location");
if (jsonLocation != null) {
String latitude = jsonLocation.getString("latitude");
String longitude = jsonLocation.getString("longitude");
location = new Location(AppLocation.class.getName());
location.setLatitude(Double.parseDouble(latitude));
location.setLongitude(Double.parseDouble(longitude));
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
Я надеюсь, что смогу вам помочь.