Android之应用APN、WIFI、GPS定位小例子
转自一个网上项目,由于是例子打包下载,出处不详。例子中自我写入注释。
Activity类:
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")
@Override
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超时了");
}
@Override
public void gpsConnected(GpsData gpsdata) {
do_gps(gpsdata);
}
}, 30 * 1000);
gpstask.execute();
break;
//进行wifi定位
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,
AddressTask.DO_APN).doApnPost();
} catch (Exception e) {
e.printStackTrace();
}
if(location == null)
return null;
return location.toString();
}
//异步操作前执行dialog显示
@Override
protected void onPreExecute() {
dialog.show();
super.onPreExecute();
}
//异步操作后显示相关信息并且关闭dialog
@Override
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) {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
MLocation location = null;
try {
Log.i("do_gpspost", "经纬度" + gpsdata.getLatitude() + "----" + gpsdata.getLongitude());
//gps定位具体操作
location = new AddressTask(GpsActivity.this,
AddressTask.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,
AddressTask.DO_WIFI).doWifiPost();
} catch (Exception e) {
e.printStackTrace();
}
if(location == null)
return null;
return location.toString();
}
@Override
protected void onPreExecute() {
dialog.show();
super.onPreExecute();
}
@Override
protected void onPostExecute(String result) {
if(result != null){
gps_tip.setText(result);
}else {
gps_tip.setText("WIFI定位失败了...");
}
dialog.dismiss();
super.onPostExecute(result);
}
}.execute();
}
GPS接口:
import com.maxtech.common.gps.GpsTask.GpsData;
public interface GpsTaskCallBack {
public void gpsConnected(GpsData gpsdata);
public void gpsConnectedTimeOut();
}
GpsTask gps的具体实现类:
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
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();
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.GPS_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 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;
}
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.app.Activity;
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;
}
@Override
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.apache.http.HttpResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
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) {
this.context = 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 {
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);
//获得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();
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);
//获得wifi相关信息
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();
}
}
Android之应用APN、WIFI、GPS定位小例子相关推荐
- android功耗(23)---gps定位开发省电要点
android手机gps定位开发省电要点 android手机使用GPS定位会非常费电.google工程师在quora上做了具体的解释,有兴趣可以看看 https://www.quora.com/Bat ...
- Android 通过Service 实现后台GPS定位
前言 做移动GIS开发经常会使用到定位功能,很多时候通过代码里的手写定位代码在Activity中就实现了.虽然比较简单,但是也会有一些问题,比如定位慢,代码杂乱.一直都知道可以通过Service进行后 ...
- iphone gps android,iPhoneX与iPhone8出现GPS定位不准故障 新版iOS系统或能修复
[TechWeb报道]11月10日消息,据国外媒体AppleInsider报道,在苹果社区支持论坛上,不断有帖子表明,iPhone X和iPhone 8手机在GPS定位的精度上出现了问题,但最新的iO ...
- Android百度地图调用和GPS定位
1.声明权限内容 其中的百度地图的key需要在百度地图的开发者上申请 申请key需要用到包名和SHA1 Window→preference→Android→Build 中有 package=" ...
- Android GPS定位及实例
使用GPS 定位,首先,需要在清单文件(AndroidManifest.xml)中注册获取定位的权限: 1.获取位置管理器对象LocationManager import android.locati ...
- android使用高德地图SDK获取定位信息
注册账号.创建应用.获取API KEY等这些就不说了,按照官网来就行,我们来讲讲项目的配置及示例代码. 高德地图获取定位信息配置要比百度地图简单多了,这是我比较喜欢的一点,而且之前用百度地图嵌入一个应 ...
- (二)WI-FI辅助定位
最早做Wi-Fi定位的是Skyhook.IPhone/IOS开始也用Skyhook,但从4.0开始,苹果开始用自己的数据库,Skyhook被无情的抛弃.Apple自己的定位数据库建立很顺理成章:Sky ...
- 高德地图八:手机定位和GPS定位
高德地图八:手机定位和GPS定位 高德地图八:手机定位和GPS定位 代码实现: layout/activity_main.xml <?xml version="1.0" en ...
- GPS定位流程_(1)
GPS定位流程_(1) 1.1 Android定位架构 整个定位服务的架构如上图 所示.该结构共分为五层: 第一层是应用层,app层,需要定位服务的客户端. 第二层是框架层,这一层实现了系统服务,主要 ...
最新文章
- 【matlab】第三章数组和数组的运算
- python字典键值可以是元组吗_python元组与字典
- qchart 设置线颜色_实战PyQt5: 137-QChart图表之散点图
- jsonarray转liast_fastjson List转JSONArray以及JSONArray转List
- 数值计算方法(五)——迭代法求方程根
- 两个形状不同的长方形周长_人教版数学六年级上册 5.2:圆的周长 微课视频|知识点|课件解析|同步练习...
- CSU 1027 Smallbox魔方
- 2级c语言题库及答案,计算机二级c语言考试题库及答案
- 机房巡检为什么检查指示灯_小工具需要“检查引擎”指示灯
- 树莓派CM4_Tiny(双HDMI)扩展板运行Openwrt演示(有线以太网)
- windows放到Linux替换,windows过渡到linux之软件的替换
- 串口接收完整一帧数据包的3种方法
- 外联式 vue+element ui 表格导出e'xcel
- python - 数据类型
- 人工智能 python 考证_写人作文
- ClickHouse压缩率
- android webView 全屏播放网络视频
- vscode上利用screen命令跑代码
- SAP英语专栏:第1篇
- zephir-基本语法
热门文章
- Linux文件和目录权限:chmod、更改所有者和所属组:chown,umask命令,隐藏权限:lsattr/chattr...
- 敏捷制造:并不是你想像的矛盾体
- Delphi WinExec ShellExec 用法介绍
- Java 基础【09】你的多继承纳?
- 软件项目开发过程中主要遇到的核心问题小结
- 分析android动画模块[转]
- JS实现sleep功能 JS遍历document对象
- 怎么在matlab中图像中外接矩形,Matlab 最小外接矩形
- Mysql循环语句,死循环解决办法
- 利用正则表达式截取特定字符中间字符