前言:
GPS定位能提供精确,详细的数据。但是有的时候我们不能通过GPS获得数据,如在屋子里面,无GPS功能等情况。那我们就需要其他的定位手段,基站定位是一个不错的选择。
当我们手机开机时,手机会自动向信号最强的无线通讯台联系,注册信息,这个通讯台就是我们所说的基站,每个基站都有自己的id,我们通过这个基站的id能够找到基站的位置,而国内城市的基站密度可以达到500米以下或者更低,所以能够大体上确定我们的位置。
准备工具:
1.TelephonyManager:主要提供了一系列用于访问与手机通讯相关的状态和信息的get方法。其中包括手机SIM的状态和信息、电信网络的状态及手机用户的信息。在这里我们就是通过这个类获得基站信息。
2.GsmCellLocation:装载着从TelephonyManager中获得的信息。
3.JSONObject,JSONArray:组建json相关的类。
4.联网相关的类。
代码:->
1.启动按钮和画板
mTextView=
(TextView) findViewById(R.id.textview);
mButton=
(Button) findViewById(R.id.button);
2.获得基站信息
mTManagerthis
.getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocationgcl
= (GsmCellLocation)mTManager.getCellLocation();
intcid
= gcl.getCid();
intlac
= gcl.getLac();
intmcc
= Integer.valueOf(mTManager.getNetworkOperator().substring(0,
3));
intmnc
= Integer.valueOf(mTManager.getNetworkOperator().substring(3,
5));
String getNumber ="";
getNumber += ("cid:"+cid
+"\n");
getNumber += ("cid:"+lac
+"\n");
getNumber += ("cid:"+mcc
+"\n");
移动国家号
getNumber += ("cid:"+mnc
+"\n");
移动网络号
3.创建json
try{
JSONObjectjObject
=newJSONObject();
jObject.put("version","1.1.0");
jObject.put("host","maps.google.com");
jObject.put("request_address",true);
if(mcc
== 460) {
jObject.put("address_language","zh_CN");
}else{
jObject.put("address_language","en_US");
}
JSONArray jArray =newJSONArray();
JSONObject jData =newJSONObject();
jData.put("cell_id",
cid);
jData.put("location_area_code",
lac);
jData.put("mobile_country_code",
mcc);
jData.put("mobile_network_code",
mnc);
jArray.put(jData);
jObject.put("cell_towers",
jArray);
4.创建连接,发送请求并接受回应
DefaultHttpClient client =newDefaultHttpClient();
HttpPost post =newHttpPost(
"http://www.google.com/loc/json");
StringEntity se =newStringEntity(jObject.toString());
post.setEntity(se);
HttpResponse resp = client.execute(post);
BufferedReader br =null;
if(resp.getStatusLine().getStatusCode()
== HttpStatus.SC_OK)
{
br =newBufferedReader(
newInputStreamReader(resp.getEntity().getContent()));
StringBuffer sb =newStringBuffer();
}
5.获得数据参见json
Server Response
StringBuffer sb =newStringBuffer();
String result = br.readLine();
while(result
!=null)
{
sb.append(getNumber);
sb.append(result);
result = br.readLine();
}
mTextView.setText(sb.toString());
添加相关permission: