---
title: "android 基于基站，apn,gps,wifi,network 根据不同手机sim卡获取经纬度"
author: "hack_zhang"
date: "2013-05-20T15:08:27Z"
tags: []
categories: ["移动开发"]
slug: "android-apn-gps-wifi-network-sim"
draft: false
lastmod: "2013-05-20T15:08:27Z"
id: 1872147
url: "https://hack-zhang.iteye.com/blog/1872147"
---

一：新建MyLocation类，本类主要管理使用各种获取经纬度的方法，由于代码比较多就不一一解释直接上代码：

 

Java代码  [![收藏代码](http://104zz.iteye.com/images/icon_star.png)]()

001. package com.android.location2;
002. import java.io.BufferedReader;
003. import java.io.IOException;
004. import java.io.InputStreamReader;
005. import java.io.UnsupportedEncodingException;
006. import java.util.ArrayList;
007. import org.apache.http.HttpEntity;
008. import org.apache.http.HttpResponse;
009. import org.apache.http.client.ClientProtocolException;
010. import org.apache.http.client.methods.HttpPost;
011. import org.apache.http.entity.StringEntity;
012. import org.apache.http.impl.client.DefaultHttpClient;
013. import org.json.JSONArray;
014. import org.json.JSONException;
015. import org.json.JSONObject;
016. import android.app.Activity;
017. import android.content.Context;
018. import android.location.Location;
019. import android.location.LocationManager;
020. import android.os.AsyncTask;
021. import android.telephony.TelephonyManager;
022. import android.telephony.cdma.CdmaCellLocation;
023. import android.widget.Toast;
024. import com.android.gps.AddressTask;
025. import com.android.gps.CellIDInfo;
026. import com.android.gps.GpsTask;
027. import com.android.gps.GpsTask.GpsData;
028. import com.android.gps.GpsTaskCallBack;
029. import com.android.gps.IAddressTask;
030. import com.android.gps.IAddressTask.MLocation;
031. public class MyLocation {
032. private LocationCallBack callBack;
033. private boolean status = false;
034. public MyLocation(LocationCallBack callBack, Activity cxt) {
035. this.callBack = callBack;
036. if (getMobileType(cxt) == 3) {
037. TelephonyManager tm = (TelephonyManager) cxt
038. .getSystemService(Context.TELEPHONY\_SERVICE);
039. CdmaCellLocation location = (CdmaCellLocation) tm.getCellLocation();
040. if (location == null)
041. return;
042. int sid = location.getSystemId();// 系统标识 mobileNetworkCode
043. int bid = location.getBaseStationId();// 基站小区号 cellId
044. int nid = location.getNetworkId();// 网络标识 locationAreaCode
045. ArrayList&lt;CellIDInfo&gt; CellID = new ArrayList&lt;CellIDInfo&gt;();
046. CellIDInfo info = new CellIDInfo();
047. info.cellId = bid;
048. info.locationAreaCode = nid;
049. info.mobileNetworkCode = String.valueOf(sid);
050. info.mobileCountryCode = tm.getNetworkOperator().substring(0, 3);
051. info.mobileCountryCode = tm.getNetworkOperator().substring(3, 5);
052. info.radioType = "cdma";
053. CellID.add(info);
054. Location mLocation = callGear(CellID);
055. if (mLocation != null) {
056. callBack.onCurrentLocation(mLocation.getLatitude(),
057. mLocation.getLongitude());
058. }
059. } else {
060. Location mLocation = getLocation(cxt);
061. if (mLocation != null) {
062. callBack.onCurrentLocation(mLocation.getLatitude(),
063. mLocation.getLongitude());
064. } else {
065. getMeLocation(cxt);
066. }
067. }
068. }
069. public interface LocationCallBack {
070. void onCurrentLocation(double latitude, double longitude);
071. }
072. // 调用google gears的方法，该方法调用gears来获取经纬度
073. private Location callGear(ArrayList&lt;CellIDInfo&gt; cellID) {
074. if (cellID == null)
075. return null;
076. DefaultHttpClient client = new DefaultHttpClient();
077. HttpPost post = new HttpPost("http://www.google.com/loc/json");
078. JSONObject holder = new JSONObject();
079. try {
080. holder.put("version", "1.1.0");
081. holder.put("host", "maps.google.com");
082. holder.put("home\_mobile\_country\_code",
083. cellID.get(0).mobileCountryCode);
084. holder.put("home\_mobile\_network\_code",
085. cellID.get(0).mobileNetworkCode);
086. holder.put("radio\_type", cellID.get(0).radioType);
087. holder.put("request\_address", true);
088. if ("460".equals(cellID.get(0).mobileCountryCode))
089. holder.put("address\_language", "zh\_CN");
090. else
091. holder.put("address\_language", "en\_US");
092. JSONObject data, current\_data;
093. JSONArray array = new JSONArray();
094. current\_data = new JSONObject();
095. current\_data.put("cell\_id", cellID.get(0).cellId);
096. current\_data.put("location\_area\_code",
097. cellID.get(0).locationAreaCode);
098. current\_data.put("mobile\_country\_code",
099. cellID.get(0).mobileCountryCode);
100. current\_data.put("mobile\_network\_code",
101. cellID.get(0).mobileNetworkCode);
102. current\_data.put("age", 0);
103. current\_data.put("signal\_strength", -60);
104. current\_data.put("timing\_advance", 5555);
105. array.put(current\_data);
106. holder.put("cell\_towers", array);
107. StringEntity se = new StringEntity(holder.toString());
108. post.setEntity(se);
109. HttpResponse resp = client.execute(post);
110. HttpEntity entity = resp.getEntity();
111. BufferedReader br = new BufferedReader(new InputStreamReader(
112. entity.getContent()));
113. StringBuffer sb = new StringBuffer();
114. String result = br.readLine();
115. while (result != null) {
116. sb.append(result);
117. result = br.readLine();
118. }
119. data = new JSONObject(sb.toString());
120. data = (JSONObject) data.get("location");
121. Location loc = new Location(LocationManager.NETWORK\_PROVIDER);
122. loc.setLatitude((Double) data.get("latitude"));
123. loc.setLongitude((Double) data.get("longitude"));
124. loc.setAccuracy(Float.parseFloat(data.get("accuracy").toString()));
125. loc.setTime(System.currentTimeMillis());// AppUtil.getUTCTime());
126. return loc;
127. } catch (JSONException e) {
128. e.printStackTrace();
129. return null;
130. } catch (UnsupportedEncodingException e) {
131. e.printStackTrace();
132. } catch (ClientProtocolException e) {
133. e.printStackTrace();
134. } catch (IOException e) {
135. e.printStackTrace();
136. }
137. return null;
138. }
139. @SuppressWarnings("unchecked")
140. public void getMeLocation(final Activity cxt) {
141. do\_apn(cxt);
142. if (status) {
143. status = false;
144. do\_wifi(cxt);
145. } else if (status) {
146. status = false;
147. GpsTask gpstask = new GpsTask(cxt, new GpsTaskCallBack() {
148. public void gpsConnectedTimeOut() {
149. Toast.makeText(cxt, "Error", Toast.LENGTH\_LONG).show();
150. }
151. public void gpsConnected(GpsData gpsdata) {
152. do\_gps(gpsdata, cxt);
153. }
154. }, 3000);
155. gpstask.execute();
156. }
157. }
158. private void do\_apn(final Activity cxt) {
159. new AsyncTask&lt;Void, Void, MLocation&gt;() {
160. protected MLocation doInBackground(Void... params) {
161. MLocation location = null;
162. try {
163. location = new AddressTask(cxt, IAddressTask.DO\_APN)
164. .doApnPost();
165. } catch (Exception e) {
166. e.printStackTrace();
167. }
168. if (location != null)
169. return location;
170. else
171. return null;
172. }
173. protected void onPreExecute() {
174. super.onPreExecute();
175. }
176. protected void onPostExecute(MLocation result) {
177. if (result != null) {
178. setData(result);
179. status = true;
180. } else {
181. status = false;
182. }
183. super.onPostExecute(result);
184. }
185. }.execute();
186. }
187. private void do\_gps(final GpsData gpsdata, final Activity cxt) {
188. new AsyncTask&lt;Void, Void, MLocation&gt;() {
189. protected MLocation doInBackground(Void... params) {
190. MLocation location = null;
191. try {
192. location = new AddressTask(cxt, IAddressTask.DO\_GPS)
193. .doGpsPost(gpsdata.getLatitude(),
194. gpsdata.getLongitude());
195. } catch (Exception e) {
196. e.printStackTrace();
197. }
198. return location;
199. }
200. protected void onPreExecute() {
201. super.onPreExecute();
202. }
203. protected void onPostExecute(MLocation result) {
204. // gps\_tip.setText(result);
205. if (result != null) {
206. setData(result);
207. status = true;
208. } else {
209. status = false;
210. }
211. super.onPostExecute(result);
212. }
213. }.execute();
214. }
215. private void do\_wifi(final Activity cxt) {
216. new AsyncTask&lt;Void, Void, MLocation&gt;() {
217. protected MLocation doInBackground(Void... params) {
218. MLocation location = null;
219. try {
220. location = new AddressTask(cxt, IAddressTask.DO\_WIFI)
221. .doWifiPost();
222. } catch (Exception e) {
223. e.printStackTrace();
224. }
225. if (location == null) {
226. return null;
227. } else
228. return location;
229. }
230. protected void onPreExecute() {
231. super.onPreExecute();
232. }
233. protected void onPostExecute(MLocation result) {
234. if (result != null) {
235. setData(result);
236. status = true;
237. } else {
238. status = false;
239. }
240. super.onPostExecute(result);
241. }
242. }.execute();
243. }
244. private void setData(MLocation result) {
245. callBack.onCurrentLocation(result.getLatitude(), result.getLongitude());
246. }
247. // Get the Location by GPS or WIFI
248. public Location getLocation(Context context) {
249. LocationManager locMan = (LocationManager) context
250. .getSystemService(Context.LOCATION\_SERVICE);
251. Location location = locMan
252. .getLastKnownLocation(LocationManager.GPS\_PROVIDER);
253. if (location == null) {
254. location = locMan
255. .getLastKnownLocation(LocationManager.NETWORK\_PROVIDER);
256. }
257. return location;
258. }
259. private int getMobileType(Context context) {
260. TelephonyManager iPhoneManager = (TelephonyManager) context
261. .getSystemService(Context.TELEPHONY\_SERVICE);
262. String iNumeric = iPhoneManager.getSimOperator();
263. if (iNumeric.length() &gt; 0) {
264. if (iNumeric.equals("46000") || iNumeric.equals("46002")) {
265. return 1;
266. } else if (iNumeric.equals("46001")) {
267. return 2;
268. } else if (iNumeric.equals("46003")) {
269. return 3;
270. }
271. }
272. return 1;
273. }
274. }

 

 

二：在MainActivity 中实现LocationCallBack接口，如下：

 

Java代码  [![收藏代码](http://104zz.iteye.com/images/icon_star.png)]()

01. import android.app.Activity;
02. import android.os.Bundle;
03. import android.widget.TextView;
04. import com.android.location2.MyLocation.LocationCallBack;
05. public class MainActivity extends Activity implements LocationCallBack{
06. private TextView desText;
07. @Override
08. public void onCreate(Bundle savedInstanceState) {
09. super.onCreate(savedInstanceState);
10. setContentView(R.layout.activity\_main);
11. desText = (TextView) this.findViewById(R.id.text);
12. new MyLocation(MainActivity.this, this);
13. }
14. //回调方法
15. public void onCurrentLocation(double latitude, double longitude) {
16. desText.setText("当前经度：" + longitude + "\\n当前纬度："+ latitude);
17. }
18. }

 

 

三：获取经纬度使用的辅助类，这里补贴代码后面直接上传源码：

![](http://dl.iteye.com/upload/attachment/0074/0143/07f13edf-7918-3613-a3cc-96e2ebcb0819.png)

四：效果如下图：

![](http://dl.iteye.com/upload/attachment/0074/0145/205ab761-bc74-3397-a814-4ea5df765317.png)