1 获取基站信息
需要用到的类:
1.android.telephony.TelephonyManager类
此类用于访问设备上的电话通讯服务的信息。此类不能直接实例化,需由 Context.getSystemService(Context.TELEPHONY_SERVICE)获取其实例。此外访问电话通讯服务的信息需要相应的权限(代码部分有说明)。
2.GsmCellLocation类
此类封装了GSM移动电话的基站信息。
3代码实现:
//获取TelephonyManager实例
TelephonyManager tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//获取封装了基站信息的GsmCellLocation对象(此函数调用需要ACCESS_COARSE_LOCATION或者ACCESS_FINE_LOCATION权限)
GsmCellLocation gsm = (GsmCellLocation) tManager.getCellLocation();
//得到LAC
int lac = gsm.getLac();
//得到CID
int cid = gsm.getCid();
1.2 获取GPS信息
获取GPS的步骤:
1.在Activity或Service中通过android.content.Context父类的方法获取LocationManager对象:
mLocMgr =(LocationManager)getSystemService(LOCATION_SERVICE);
2.给要获取GPS数据的对象注册GPS监听器,通过LocationManager的requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)方法进行注册
参数列表:
provider要注册的Provider,这里为LocationManager.GPS_PROVIDER
minTime 接受数据的最小的时间间隔,单位毫秒。这个时间不一定准确,不过要注意的是更新时间间隔也短越耗电
minDistance 进行更新的最小距离,单位米
Listener 要监听GPS数据的对象。
要注意:如果一直打开GPS会十分消耗电量,所以一般要设置一个较大的minTime值,一般不要小于60000
注意:调用requestLocationUpdates的线程必须有一个Looper,如果线程没有Looper,可以调用Loop.prepare()为该线程建立一个消息队列。
相应代码:
mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0,listener);
3.通过监听器获取数据
LocationListener listener =new LocationListener() {
//位置改变时的回调方法
@Override
publicvoid onLocationChanged(Location loc) {
if (loc !=null) {
//获取经度数据
loc.getLongitude();
//获取纬度数据
loc.getLatitude();
}
}
//GPS被用户禁用的回调方法
@Override
publicvoid onProviderDisabled(String arg0) {
//TODO Auto-generated method stub
}
//GPS被用户开启的回调方法
@Override
publicvoid onProviderEnabled(String arg0) {
//TODO Auto-generated method stub
}
//GPS状态改变的回调方法
@Override
publicvoid onStatusChanged(String arg0,int arg1, Bundle arg2) {
//TODO Auto-generated method stub
}
};
如果要节约电量,可以在onLocationChanged()回调方法中每次获取经纬度数据后调用LocationManager对象的removeUpdates(listener);方法注销已经注册的监听器,这要就不会再接受GPS数据的更新。
此外LocationManager类还提供了一个getLastKnownLocation(String provider)的方法,此方法返回一个Location对象,我们可以通过getLastKnownLocation(LocationManager.GPS_PROVIDER)获取最后一个获取到的GPS数据,数据封装在Location对象中。但此方法提供的数据有可能是过时的,因为用户可能关掉手机到达另外一个新地点。如果GPS被禁用此方法返回 null.如果一直没有调用LocationManager.requestLocationUpdates()注册GPS监听器获取数据,getLastKnownLocation每次返回的值都一样。
获取GPS信息需要以下两种权限:
<uses-permission android:name="android.permission.LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
实际只需
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />权限即可。
1.3 获取MCC和MNC
TelephonyManager tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
返回MCC+MNC
String info = tManager.getNetworkOperator();
用wifi 获取
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);
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
1.4 技术实现方式
1.4.1 获取LBS信息
要获取LAC或MMC或MNC信息都比较容易,只要把上述代码简单封装成一个类,然后在传给这个类一个CONTEXT对象,就可以随时获取所需信息。
1.4.2 获取GPS信息
要获取GPS数据,目前有以下2种方法:
1)做一个SERVICE对象,让这个SERVICE一直监听GPS数据,我们可以通过绑定这个SERVICE获取到最近更新的GPS数据。
2)直接通过LocationManager.getLastKnownLocation()方法得到GPS设备最后一次获取的位置
废话不多少 下面贴出三种方式实现代码
// 活动 操作各个按钮通过不同方式获取位置信息
public class GpsActivity extends Activity implements OnClickListener {
private TextView gps_tip = null;
private AlertDialog dialog = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gps_tip = (TextView) findViewById(R.id.gps_tip);
findViewById(R.id.do_gps).setOnClickListener(GpsActivity.this);
findViewById(R.id.do_apn).setOnClickListener(GpsActivity.this);
findViewById(R.id.do_wifi).setOnClickListener(GpsActivity.this);
dialog = new ProgressDialog(GpsActivity.this);
dialog.setTitle("请稍等...");
dialog.setMessage("正在定位...");
}
@SuppressWarnings("unchecked")
@Override
public void onClick(View v) {
gps_tip.setText("");
switch (v.getId()) {
case R.id.do_apn:
do_apn();
break;
case R.id.do_gps:
GpsTask gpstask = new GpsTask(GpsActivity.this,
new GpsTaskCallBack() {
@Override
public void gpsConnectedTimeOut() {
gps_tip.setText("获取GPS超时了");
}
@Override
public void gpsConnected(GpsData gpsdata) {
do_gps(gpsdata);
}
}, 3000);
gpstask.execute();
break;
case R.id.do_wifi:
do_wifi();
break;
}
}
private void do_apn() {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
MLocation location = null;
try {
location = new AddressTask(GpsActivity.this,
IAddressTask.DO_APN).doApnPost();
} catch (Exception e) {
e.printStackTrace();
}
return location.toString();
}
@Override
protected void onPreExecute() {
dialog.show();
super.onPreExecute();
}
@Override
protected void onPostExecute(String result) {
gps_tip.setText(result);
dialog.dismiss();
super.onPostExecute(result);
}
}.execute();
}
private void do_gps(final GpsData gpsdata) {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
MLocation location = null;
try {
location = new AddressTask(GpsActivity.this,
IAddressTask.DO_GPS).doGpsPost(gpsdata.getLatitude(),
gpsdata.getLongitude());
} catch (Exception e) {
e.printStackTrace();
}
if(location == null)
return "GPS信息获取错误";
return location.toString();
}
@Override
protected void onPreExecute() {
dialog.show();
super.onPreExecute();
}
@Override
protected void onPostExecute(String result) {
gps_tip.setText(result);
dialog.dismiss();
super.onPostExecute(result);
}
}.execute();
}
private void do_wifi() {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
MLocation location = null;
try {
location = new AddressTask(GpsActivity.this,
IAddressTask.DO_WIFI).doWifiPost();
} catch (Exception e) {
e.printStackTrace();
}
return location.toString();
}
@Override
protected void onPreExecute() {
dialog.show();
super.onPreExecute();
}
@Override
protected void onPostExecute(String result) {
gps_tip.setText(result);
dialog.dismiss();
super.onPostExecute(result);
}
}.execute();
}
}
// 抽象类的子类实现父类的抽象方法具体实现excute方法
public class AddressTask extends IAddressTask {
public AddressTask(Activity context, int postType) {
super(context, postType);
}
@Override
public HttpResponse execute(JSONObject params) throws Exception {
HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),
20 * 1000);
HttpConnectionParams.setSoTimeout(httpClient.getParams(), 20 * 1000);
HttpPost post = new HttpPost("http://74.125.71.147/loc/json");
// 设置代理
if (postType == DO_APN) {
Uri uri = Uri.parse("content://telephony/carriers/preferapn"); // 获取当前正在使用的APN接入点
Cursor mCursor = context.getContentResolver().query(uri, null,
null, null, null);
if (mCursor != null) {
// mCursor.moveToNext(); // 游标移至第一条记录,当然也只有一条
if(mCursor.moveToFirst()) {
String proxyStr = mCursor.getString(mCursor
.getColumnIndex("proxy"));
if (proxyStr != null && proxyStr.trim().length() > 0) {
HttpHost proxy = new HttpHost(proxyStr, 80);
httpClient.getParams().setParameter(
ConnRouteParams.DEFAULT_PROXY, proxy);
}
}
}
}
StringEntity se = new StringEntity(params.toString());
post.setEntity(se);
HttpResponse response = httpClient.execute(post);
return response;
}
}
public class GpsTask extends AsyncTask {
private GpsTaskCallBack callBk = null;
private Activity context = null;
private LocationManager locationManager = null;
private LocationListener locationListener = null;
private Location location = null;
private boolean TIME_OUT = false;
private boolean DATA_CONNTECTED = false;
private long TIME_DURATION = 5000;
private GpsHandler handler = null;
private class GpsHandler extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(callBk == null)
return;
switch (msg.what) {
case 0:
callBk.gpsConnected((GpsData)msg.obj);
break;
case 1:
callBk.gpsConnectedTimeOut();
break;
}
}
}
public GpsTask(Activity context, GpsTaskCallBack callBk) {
this.callBk = callBk;
this.context = context;
gpsInit();
}
public GpsTask(Activity context, GpsTaskCallBack callBk, long time_out) {
this.callBk = callBk;
this.context = context;
this.TIME_DURATION = time_out;
gpsInit();
}
private void gpsInit() {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
handler = new GpsHandler();
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
} else {
//GPS没有打开
TIME_OUT = true;
}
locationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location l) {
DATA_CONNTECTED = true;
Message msg = handler.obtainMessage();
msg.what = 0;
msg.obj = transData(l);
handler.sendMessage(msg);
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
100, locationListener);
}
@Override
protected Object doInBackground(Object... params) {
while (!TIME_OUT && !DATA_CONNTECTED) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null && callBk != null) {
//获得上一次数据
Message msg = handler.obtainMessage();
msg.what = 0;
msg.obj = transData(location);
handler.sendMessage(msg);
break;
}
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
TIME_OUT = true;
}
}, TIME_DURATION);
}
@SuppressWarnings("unchecked")
@Override
protected void onPostExecute(Object result) {
locationManager.removeUpdates(locationListener);
// 获取超时
if (TIME_OUT && callBk != null)
handler.sendEmptyMessage(1);
super.onPostExecute(result);
}
private GpsData transData(Location location) {
GpsData gpsData = new GpsData();
gpsData.setAccuracy(location.getAccuracy());
gpsData.setAltitude(location.getAltitude());
gpsData.setBearing(location.getBearing());
gpsData.setLatitude(location.getLatitude());
gpsData.setLongitude(location.getLongitude());
gpsData.setSpeed(location.getSpeed());
gpsData.setTime(location.getTime());
return gpsData;
}
// gps 实体类定义
public static class GpsData {
private double latitude = 0;
private double longitude = 0;
private float accuracy = 0;
private double altitude = 0;
private float bearing = 0;
private float speed = 0;
private long time = 0;
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public float getAccuracy() {
return accuracy;
}
public void setAccuracy(float accuracy) {
this.accuracy = accuracy;
}
public double getAltitude() {
return altitude;
}
public void setAltitude(double altitude) {
this.altitude = altitude;
}
public float getBearing() {
return bearing;
}
public void setBearing(float bearing) {
this.bearing = bearing;
}
public float getSpeed() {
return speed;
}
public void setSpeed(float speed) {
this.speed = speed;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
}
}
// gps方式回调接口
public interface GpsTaskCallBack {
public void gpsConnected(GpsData gpsdata);
public void gpsConnectedTimeOut();
}
// 抽象类获取位置信息
public abstract class IAddressTask {
protected Activity context;
protected int postType = 0;
public static final int DO_GPS = 0;
public static final int DO_APN = 1;
public static final int DO_WIFI = 2;
public IAddressTask(Activity context, int postType) {
this.context = context;
this.postType = postType;
}
public abstract HttpResponse execute(JSONObject params) throws Exception;
public MLocation doWifiPost() throws Exception {
return transResponse(execute(doWifi()));
}
public MLocation doApnPost() throws Exception {
return transResponse(execute(doApn()));
}
public MLocation doGpsPost(double lat, double lng) throws Exception {
return transResponse(execute(doGps(lat, lng)));
}
// 解析返回值
private MLocation transResponse(HttpResponse response) {
MLocation location = null;
if (response.getStatusLine().getStatusCode() == 200) {
location = new MLocation();
HttpEntity entity = response.getEntity();
BufferedReader br;
try {
br = new BufferedReader(new InputStreamReader(
entity.getContent()));
StringBuffer sb = new StringBuffer();
String result = br.readLine();
while (result != null) {
sb.append(result);
result = br.readLine();
}
JSONObject json = new JSONObject(sb.toString());
JSONObject lca = json.getJSONObject("location");
location.Access_token = json.getString("access_token");
if (lca != null) {
if(lca.has("accuracy"))
location.Accuracy = lca.getString("accuracy");
if(lca.has("longitude"))
location.Latitude = lca.getDouble("longitude");
if(lca.has("latitude"))
location.Longitude = lca.getDouble("latitude");
if(lca.has("address")) {
JSONObject address = lca.getJSONObject("address");
if (address != null) {
if(address.has("region"))
location.Region = address.getString("region");
if(address.has("street_number"))
location.Street_number = address
.getString("street_number");
if(address.has("country_code"))
location.Country_code = address
.getString("country_code");
if(address.has("street"))
location.Street = address.getString("street");
if(address.has("city"))
location.City = address.getString("city");
if(address.has("country"))
location.Country = address.getString("country");
}
}
}
} catch (Exception e) {
e.printStackTrace();
location = null;
}
}
return location;
}
/*
*因三种方式每个需要的参数不同各自的访问参数
*/
private JSONObject doGps(double lat, double lng) throws Exception {
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);
JSONObject data = new JSONObject();
data.put("latitude", lat);
data.put("longitude", lng);
holder.put("location", data);
return holder;
}
private JSONObject doApn() throws Exception {
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);
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
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));
JSONArray array = new JSONArray();
JSONObject data = new JSONObject();
data.put("cell_id", cid);
data.put("location_area_code", lac);
data.put("mobile_country_code", mcc);
data.put("mobile_network_code", mnc);
array.put(data);
holder.put("cell_towers", array);
return holder;
}
private JSONObject doWifi() throws Exception {
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);
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if(wifiManager.getConnectionInfo().getBSSID() == null) {
throw new RuntimeException("bssid is null");
}
JSONArray array = new JSONArray();
JSONObject data = new JSONObject();
data.put("mac_address", wifiManager.getConnectionInfo().getBSSID());
data.put("signal_strength", 8);
data.put("age", 0);
array.put(data);
holder.put("wifi_towers", array);
return holder;
}
public static class MLocation {
public String Access_token;
public double Latitude;
public double Longitude;
public String Accuracy;
public String Region;
public String Street_number;
public String Country_code;
public String Street;
public String City;
public String Country;
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("Access_token:" + Access_token + "\n");
buffer.append("Region:" + Region + "\n");
buffer.append("Accuracy:" + Accuracy + "\n");
buffer.append("Latitude:" + Latitude + "\n");
buffer.append("Longitude:" + Longitude + "\n");
buffer.append("Country_code:" + Country_code + "\n");
buffer.append("Country:" + Country + "\n");
buffer.append("City:" + City + "\n");
buffer.append("Street:" + Street + "\n");
buffer.append("Street_number:" + Street_number + "\n");
return buffer.toString();
}
}
}