import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import com.own.test.TestActivity;
public class LocationManage {
public static void getLocation() {
// 通过基站 定位
new Thread() {
public void run() {
List list = null;
try {
list = LocationManage.getCellIDInfo(TestActivity.context);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (list == null || list.size() == 0) {
return;
}
Location location = LocationManage.callGear(list);
if (location == null) {
return;
}
// /////
};
}.start();
}
public static String locationAddress = "";
/*
* 获取基站信息
*/
public static ArrayList getCellIDInfo(Context context)
throws Exception {
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
ArrayList CellID = new ArrayList();
CellIDInfo currentCell = new CellIDInfo();
int type = manager.getNetworkType();
Log.d("getCellIDInfo", "getCellIDInfo--> NetworkType = " + type);
int phoneType = manager.getPhoneType();
Log.d("getCellIDInfo", "getCellIDInfo--> phoneType = " + phoneType);
// phoneType == TelephonyManager.PHONE_TYPE_GSM
if (type == TelephonyManager.NETWORK_TYPE_GPRS // GSM网
|| type == TelephonyManager.NETWORK_TYPE_EDGE
|| type == TelephonyManager.NETWORK_TYPE_HSDPA) {
GsmCellLocation gsm = ((GsmCellLocation) manager.getCellLocation());
if (gsm == null) {
Log.e("getCellIDInfo", "GsmCellLocation is null!!!");
return null;
}
int lac = gsm.getLac();
String mcc = manager.getNetworkOperator().substring(0, 3);
String mnc = manager.getNetworkOperator().substring(3, 5);
int cid = gsm.getCid();
currentCell.cellId = cid;
currentCell.mobileCountryCode = Integer.valueOf(mcc);
currentCell.mobileNetworkCode = Integer.valueOf(mnc);
currentCell.locationAreaCode = lac;
currentCell.radioType = "gsm";
CellID.add(currentCell);
// 获得邻近基站信息
List list = manager.getNeighboringCellInfo();
int size = list.size();
for (int i = 0; i < size; i++) {
CellIDInfo info = new CellIDInfo();
info.cellId = list.get(i).getCid();
info.mobileCountryCode = Integer.valueOf(mcc);
info.mobileNetworkCode = Integer.valueOf(mnc);
info.locationAreaCode = lac;
CellID.add(info);
}
// phoneType == TelephonyManager.PHONE_TYPE_CDMA
} else if (type == TelephonyManager.NETWORK_TYPE_CDMA // 电信cdma网
|| type == TelephonyManager.NETWORK_TYPE_1xRTT
|| type == TelephonyManager.NETWORK_TYPE_EVDO_0
|| type == TelephonyManager.NETWORK_TYPE_EVDO_A) {
CdmaCellLocation cdma = (CdmaCellLocation) manager
.getCellLocation();
if (cdma == null) {
Log.e("getCellIDInfo", "CdmaCellLocation is null!!!");
return null;
}
int lac = cdma.getNetworkId();
String mcc = manager.getNetworkOperator().substring(0, 3);
String mnc = String.valueOf(cdma.getSystemId());
int cid = cdma.getBaseStationId();
currentCell.cellId = cid;
currentCell.mobileCountryCode = Integer.valueOf(mcc);
currentCell.mobileNetworkCode = Integer.valueOf(mnc);
currentCell.locationAreaCode = lac;
currentCell.radioType = "cdma";
CellID.add(currentCell);
// 获得邻近基站信息
List list = manager.getNeighboringCellInfo();
int size = list.size();
for (int i = 0; i < size; i++) {
CellIDInfo info = new CellIDInfo();
info.cellId = list.get(i).getCid();
info.mobileCountryCode = Integer.valueOf(mcc);
info.mobileNetworkCode = Integer.valueOf(mnc);
info.locationAreaCode = lac;
CellID.add(info);
}
}
return CellID;
}
// 基站信息
static class CellIDInfo {
public CellIDInfo() {
}
public int cellId;// 基站id
public int mobileCountryCode;// mcc
public int mobileNetworkCode;// mnc
public int locationAreaCode;// lac
public String radioType; // gsm or cdma
}
/**
* 将基站信息 转换为 Location
*
* @param cellID
* @return
*/
public static Location callGear(List cellID) {
if (cellID == null || cellID.size() == 0)
return null;
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.google.com/loc/json");
JSONObject holder = new JSONObject();
try {
holder.put("version", "1.1.0");
holder.put("host", "maps.google.com");
holder.put("home_mobile_country_code",
cellID.get(0).mobileCountryCode);
holder.put("home_mobile_network_code",
cellID.get(0).mobileNetworkCode);
holder.put("radio_type", cellID.get(0).radioType);
holder.put("request_address", true);
if ("460".equals(cellID.get(0).mobileCountryCode))
holder.put("address_language", "zh_CN");
else
holder.put("address_language", "en_US");
JSONObject data, current_data;
JSONArray array = new JSONArray();
current_data = new JSONObject();
current_data.put("cell_id", cellID.get(0).cellId);
current_data.put("location_area_code",
cellID.get(0).locationAreaCode);
current_data.put("mobile_country_code",
cellID.get(0).mobileCountryCode);
current_data.put("mobile_network_code",
cellID.get(0).mobileNetworkCode);
// current_data.put("age", 0);
// current_data.put("signal_strength", -60);
// current_data.put("timing_advance", 5555);
array.put(current_data);
if (cellID.size() > 2) {
for (int i = 1; i < cellID.size(); i++) {
data = new JSONObject();
data.put("cell_id", cellID.get(i).cellId);
data.put("location_area_code",
cellID.get(i).locationAreaCode);
data.put("mobile_country_code",
cellID.get(i).mobileCountryCode);
data.put("mobile_network_code",
cellID.get(i).mobileNetworkCode);
// data.put("age", 0);
array.put(data);
}
}
holder.put("cell_towers", array);
StringEntity se = new StringEntity(holder.toString());
Log.e("Location send", holder.toString());
post.setEntity(se);
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(
entity.getContent()));
StringBuffer sb = new StringBuffer();
String result = br.readLine();
while (result != null) {
Log.e("Locaiton reseive-->", result);
sb.append(result);
result = br.readLine();
}
data = new JSONObject(sb.toString());
data = (JSONObject) data.get("location");
Location loc = new Location(LocationManager.NETWORK_PROVIDER);
loc.setLatitude((Double) data.get("latitude"));
loc.setLongitude((Double) data.get("longitude"));
loc.setAccuracy(Float.parseFloat(data.get("accuracy").toString()));
loc.setTime(System.currentTimeMillis());// AppUtil.getUTCTime());
return loc;
} catch (JSONException e) {
e.printStackTrace();
return null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* location -> address
*
* @param itude
* @return
* @throws Exception
*/
public static void getAddress(Location location) {
if (null == location) {
return;
}
Geocoder geo = new Geocoder(TestActivity.context);
List adds = null;
try {
adds = geo.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
if (null != adds && adds.size() > 0) {
Address a = adds.get(0);
String area = a.getAdminArea();
String city = a.getLocality();
String lity = a.getSubLocality();
String stree = a.getThoroughfare();
String result = "";
if (null != area) {
result += area;
}
if (null != city) {
result += city;
}
if (null != lity) {
result += lity;
}
if (null != stree) {
result += stree;
}
locationAddress = result;
}
// String resultString = "";
//
// /** 这里采用get方法,直接将参数加到URL上 */
// String urlString = String.format(
// "http://maps.google.cn/maps/geo?key=abcdefg&q=%s,%s",
// itude.getLatitude(), itude.getLongitude());
// Log.i("URL", urlString);
//
// /** 新建HttpClient */
// HttpClient client = new DefaultHttpClient();
// /** 采用GET方法 */
// HttpGet get = new HttpGet(urlString);
// try {
// /** 发起GET请求并获得返回数据 */
// HttpResponse response = client.execute(get);
// HttpEntity entity = response.getEntity();
// BufferedReader buffReader = new BufferedReader(
// new InputStreamReader(entity.getContent()));
// StringBuffer strBuff = new StringBuffer();
// String result = null;
// while ((result = buffReader.readLine()) != null) {
// strBuff.append(result);
// }
// resultString = strBuff.toString();
//
// Log.e("resultAdress--->", resultString);
//
// /** 解析JSON数据,获得物理地址 */
// if (resultString != null && resultString.length() > 0) {
// JSONObject jsonobject = new JSONObject(resultString);
// JSONArray jsonArray = new JSONArray(jsonobject.get("Placemark")
// .toString());
// resultString = "";
// for (int i = 0; i < jsonArray.length(); i++) {
// resultString = jsonArray.getJSONObject(i).getString(
// "address");
// }
// }
// } catch (Exception e) {
// throw new Exception("获取物理位置出现错误:" + e.getMessage());
// } finally {
// get.abort();
// client = null;
// }
//
// return resultString;
}
private static final int CHECK_INTERVAL = 1000 * 30;
/**
*
* @param location
* can't null
* @param currentBestLocation
* can be null
* @return
*/
public synchronized static boolean isBetterLocation(Location location,
Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > CHECK_INTERVAL;
boolean isSignificantlyOlder = timeDelta < -CHECK_INTERVAL;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location,
// use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must
// be worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and
// accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate
&& isFromSameProvider) {
return true;
}
return false;
}
/** Checks whether two providers are the same */
private static boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
}
这里还有一篇关于 基站,wifii定位 的文章,在Android里完美实现基站和WIFI定位