轉自一個網上項目,由于是例子打包下載下傳,出處不詳。例子中自我寫入注釋。
activity類:
package com.maxtech.common;
import com.maxtech.common.gps.gpstask;
import com.maxtech.common.gps.gpstaskcallback;
import com.maxtech.common.gps.gpstask.gpsdata;
import com.maxtech.common.gps.iaddresstask.mlocation;
import android.app.activity;
import android.app.alertdialog;
import android.app.progressdialog;
import android.os.asynctask;
import android.os.bundle;
import android.util.log;
import android.view.view;
import android.view.view.onclicklistener;
import android.widget.textview;
public class gpsactivity extends activity implements onclicklistener {
private textview gps_tip = null;
//聲明alertdialog
private alertdialog dialog = null;
@override
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.main);
//布局主要就是三個按鈕與一個textview
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);
//這個progressdialog是用于讀取資料時顯示
dialog = new progressdialog(gpsactivity.this);
dialog.settitle("請稍等...");
dialog.setmessage("正在定位...");
}
//各個按鈕的工作
@suppresswarnings("unchecked")
public void onclick(view v) {
gps_tip.settext("");
switch (v.getid()) {
case r.id.do_apn:
//進行apn的定位
do_apn();
break;
case r.id.do_gps:
//進行gps定位
gpstask gpstask = new gpstask(gpsactivity.this,
new gpstaskcallback() {
@override
public void gpsconnectedtimeout() {
gps_tip.settext("擷取gps逾時了");
}
public void gpsconnected(gpsdata gpsdata) {
do_gps(gpsdata);
}, 30 * 1000);
gpstask.execute();
//進行wifi定位
case r.id.do_wifi:
do_wifi();
}
private void do_apn() {
//異步
new asynctask<void, void, string>() {
@override
protected string doinbackground(void... params) {
mlocation location = null;
try {
//具體操作
location = new addresstask(gpsactivity.this,
addresstask.do_apn).doapnpost();
} catch (exception e) {
e.printstacktrace();
}
if(location == null)
return null;
return location.tostring();
}
//異步操作前執行dialog顯示
protected void onpreexecute() {
dialog.show();
super.onpreexecute();
//異步操作後顯示相關資訊并且關閉dialog
protected void onpostexecute(string result) {
if(result == null){
gps_tip.settext("基站定位失敗了...");
}else {
gps_tip.settext(result);
dialog.dismiss();
super.onpostexecute(result);
}.execute();
private void do_gps(final gpsdata gpsdata) {
log.i("do_gpspost", "經緯度" + gpsdata.getlatitude() + "----" + gpsdata.getlongitude());
//gps定位具體操作
addresstask.do_gps).dogpspost(gpsdata.getlatitude(),
gpsdata.getlongitude());
return "gps資訊擷取錯誤";
gps_tip.settext(result);
private void do_wifi() {
addresstask.do_wifi).dowifipost();
if(result != null){
gps_tip.settext("wifi定位失敗了...");
}
gps接口:
package com.maxtech.common.gps;
public interface gpstaskcallback {
public void gpsconnected(gpsdata gpsdata);
public void gpsconnectedtimeout();
}
gpstask gps的具體實作類:
import java.util.timer;
import java.util.timertask;
import android.content.context;
import android.location.location;
import android.location.locationlistener;
import android.location.locationmanager;
import android.os.handler;
import android.os.message;
@suppresswarnings("rawtypes")
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();
}
public gpstask(activity context, gpstaskcallback callbk) {
this.callbk = callbk;
this.context = context;
gpsinit();
public gpstask(activity context, gpstaskcallback callbk, long time_out) {
this.time_duration = time_out;
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() {
public void onstatuschanged(string provider, int status,
bundle extras) {
public void onproviderenabled(string provider) {
public void onproviderdisabled(string provider) {
//位置改變才會調用
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);
protected object doinbackground(object... params) {
while (!time_out && !data_conntected) {
location = locationmanager
.getlastknownlocation(locationmanager.gps_provider);
if (location != null && callbk != null) {
//�����һ�����
msg.obj = transdata(location);
break;
return null;
protected void onpreexecute() {
super.onpreexecute();
//timer是自動另外開的一條線程
timer timer = new timer();
timer.schedule(new timertask() {
public void run() {
time_out = true;
}, time_duration);
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;
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;
}
addresstask 使用post通路的參數設定
import org.apache.http.httphost;
import org.apache.http.httpresponse;
import org.apache.http.client.httpclient;
import org.apache.http.client.methods.httppost;
import org.apache.http.conn.params.connrouteparams;
import org.apache.http.entity.stringentity;
import org.apache.http.impl.client.defaulthttpclient;
import org.apache.http.params.httpconnectionparams;
import org.json.jsonobject;
import android.net.proxy;
import com.maxtech.common.gps.iaddresstask;
public class addresstask extends iaddresstask {
public static final int do_apn = 0;
public static final int do_wifi = 1;
public static final int do_gps = 2;
private int posttype = -1;
public addresstask(activity context, int posttype) {
super(context);
this.posttype = posttype;
public httpresponse execute(jsonobject params) throws exception {
httpclient httpclient = new defaulthttpclient();
httpconnectionparams.setconnectiontimeout(httpclient.getparams(),
20 * 1000);
httpconnectionparams.setsotimeout(httpclient.getparams(), 20 * 1000);
//通路json
httppost post = new httppost("http://74.125.71.147/loc/json");
// 設定代理
if (posttype == do_apn) {
string proxyhost = proxy.getdefaulthost();
if(proxyhost != null) {
httphost proxy = new httphost(proxyhost, 80);
httpclient.getparams().setparameter(
connrouteparams.default_proxy, proxy);
//請求一系列的參數
stringentity se = new stringentity(params.tostring());
post.setentity(se);
httpresponse response = httpclient.execute(post);
return response;
iaddresstask apn、wifi、gps具體實作類:
import java.io.bufferedreader;
import java.io.inputstreamreader;
import org.apache.http.httpentity;
import org.json.jsonarray;
import android.net.wifi.wifimanager;
import android.telephony.telephonymanager;
import android.telephony.gsm.gsmcelllocation;
public abstract class iaddresstask {
protected activity context;
public iaddresstask(activity context) {
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.longitude = lca.getdouble("longitude");
if(lca.has("latitude"))
location.latitude = 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 {
//獲得gsm相關資訊
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();
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);
private jsonobject dowifi() throws exception {
//獲得wifi相關資訊
wifimanager wifimanager = (wifimanager) context.getsystemservice(context.wifi_service);
if(wifimanager.getconnectioninfo().getbssid() == null) {
throw new runtimeexception("bssid is null");
data.put("mac_address", wifimanager.getconnectioninfo().getbssid());
data.put("signal_strength", 8);
data.put("age", 0);
holder.put("wifi_towers", array);
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();