Android 获取GPS位置,包含apn\wifi\gps



一部分:几种定位简述

1.gps定位:
 
优点:最简单的手机定位方式当然是通过GPS模块(现在大部分的智能机应该都有了)。GPS方式准确度是最高的
缺点1.比较耗电;
       2.绝大部分用户默认不开启GPS模块;
       3.从GPS模块启动到获取第一次定位数据,可能需要比较长的时间;
       4.室内几乎无法使用。
这其中,缺点2,3都是比较致命的。需要指出的是,GPS走的是卫星通信的通道,在没有网络连接的情况下也能用。
 
有网络、室内不可用、定位时间长、位置精确
 
2.基站定位
大致思路就是采集到手机上的基站ID号(cellid)和其它的一些信息(MNC,MCC,LAC等等),然后通过网络访问一些定位服务,获取并返回对应的经纬度坐标。基站定位的精确度不如GPS,好处是能够在室内用,只要网络通畅就行。
 
有网络 室内可用 定位方式不精确
 
3.WIFI定位
和基站定位类似,这种方式是通过获取当前所用的wifi的一些信息,然后访问网络上的定位服务以获得经纬度坐标。因为它和基站定位其实都需要使用网络,所以在Android也统称为Network方式。
 
与基站定位类似
 
4.AGPS定位
最后需要解释一点的是AGPS方式。很多人将它和基站定位混为一谈,但其实AGPS的本质仍然是GPS,只是它会使用基站信息对获取GPS进行辅助,然后还能对获取到的GPS结果进行修正,所以AGPS要比传统的GPS更快,准确度略高。
 
有网络、类似gps定位、但比传统Gps定位更快,准确度略高
 
第二部分
locationManager.getLastKnownLocation()总是会出现取不到数据的情况,所以这里没有使用这个方法,避免了取不到数据的问题
 
第三部分:使用异步加载,提高性能
 
================================代码===========================
 

  

 

 

1.Activity

 

  1. package com.example.gpsdemo;  
  2.  
  3. import com.example.gpsdemo.util.GetLocation;  
  4. import com.example.gpsdemo.util.LMLocation;  
  5.  
  6. import android.app.Activity;  
  7. import android.app.AlertDialog;  
  8. import android.app.ProgressDialog;  
  9. import android.os.Bundle;  
  10. import android.view.View;  
  11. import android.view.View.OnClickListener;  
  12. import android.widget.Button;  
  13. import android.widget.TextView;  
  14.  
  15. public class MainActivity extends Activity {  
  16.     LMLocation lmLocation;  
  17.     TextView textView;  
  18.     public MainActivity instance;  
  19.     private AlertDialog dialog;  
  20.     @Override 
  21.     public void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.activity_main);  
  24.         textView = (TextView) findViewById(R.id.textView2);  
  25.         instance = this;  
  26.         dialog = new ProgressDialog(MainActivity.this);  
  27.         dialog.setTitle("请稍等...");  
  28.         dialog.setMessage("正在定位...");  
  29.         Button button = (Button) findViewById(R.id.button1);  
  30.         button.setOnClickListener(new OnClickListener() {  
  31.  
  32.             @Override 
  33.             public void onClick(View v) {  
  34.                 // TODO Auto-generated method stub  
  35.                 new GetLocation(dialog, textView, instance).DisplayLocation();  
  36.             }  
  37.         });  
  38.  
  39.     }  
  40.  
  41. }  
 
 2.与MainActivity对应的布局
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  2.     xmlns:tools="http://schemas.android.com/tools" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" > 
  5.  
  6.     <TextView 
  7.         android:id="@+id/textView2" 
  8.         android:layout_width="wrap_content" 
  9.         android:layout_height="wrap_content" 
  10.         android:layout_centerHorizontal="true" 
  11.         android:layout_centerVertical="true" 
  12.         android:padding="@dimen/padding_medium" 
  13.         android:text="@string/hello_world" 
  14.         tools:context=".MainActivity" /> 
  15.  
  16.     <Button 
  17.         android:id="@+id/button1" 
  18.         android:layout_width="wrap_content" 
  19.         android:layout_height="wrap_content" 
  20.         android:layout_alignParentTop="true" 
  21.         android:layout_alignRight="@+id/textView2" 
  22.         android:layout_marginRight="52dp" 
  23.         android:text="定位" /> 
  24.  
  25. </RelativeLayout> 

3.AndroidManifest.xml

  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android" 
  2.     package="com.example.gpsdemo" 
  3.     android:versionCode="1" 
  4.     android:versionName="1.0" > 
  5.  
  6.     <uses-sdk 
  7.         android:minSdkVersion="8" 
  8.         android:targetSdkVersion="15" /> 
  9.  
  10.     <application 
  11.         android:icon="@drawable/ic_launcher" 
  12.         android:label="@string/app_name" 
  13.         android:theme="@style/AppTheme" > 
  14.         <activity 
  15.             android:name=".MainActivity" 
  16.             android:label="@string/title_activity_main" > 
  17.             <intent-filter> 
  18.                 <action android:name="android.intent.action.MAIN" /> 
  19.  
  20.                 <category android:name="android.intent.category.LAUNCHER" /> 
  21.             </intent-filter> 
  22.         </activity> 
  23.     </application> 
  24.       <!-- 获取地理位置权限 --> 
  25.      <uses-permission android:name="android.permission.INTERNET" /> 
  26.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
  27.     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
  28.     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
  29.     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 
  30.     <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission> 
  31.     <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission> 
  32.  
  33. </manif 

 

 

4.工具类两个:(1)

 

  1. package com.example.gpsdemo.util;  
  2.  
  3. import android.app.AlertDialog;  
  4. import android.content.Context;  
  5. import android.os.AsyncTask;  
  6. import android.util.Log;  
  7. import android.widget.TextView;  
  8.  
  9. public class GetLocation {  
  10.     AlertDialog dialog;  
  11.     TextView textView;  
  12.     Context context;  
  13.  
  14.     public GetLocation(AlertDialog dialog, TextView textView, Context context) {  
  15.         this.dialog = dialog;  
  16.         this.textView = textView;  
  17.         this.context = context;  
  18.  
  19.     }  
  20.  
  21.     public void DisplayLocation() {  
  22.         new AsyncTask<Void, Void, String>() {  
  23.  
  24.             @Override 
  25.             protected String doInBackground(Void... params) {  
  26.                 LMLocation location = null;  
  27.                 try {  
  28.                     location = new GPSLocation().getGPSInfo(context);  
  29.                 } catch (Exception e) {  
  30.                     // TODO Auto-generated catch block  
  31.                     e.printStackTrace();  
  32.                 }  
  33.                 if (location == null)  
  34.                     return null;  
  35.                 Log.d("debug", location.toString());  
  36.                 return location.toString();  
  37.  
  38.             }  
  39.  
  40.             @Override 
  41.             protected void onPreExecute() {  
  42.                 dialog.show();  
  43.                 super.onPreExecute();  
  44.             }  
  45.  
  46.             @Override 
  47.             protected void onPostExecute(String result) {  
  48.                 if (result == null) {  
  49.                     textView.setText("定位失败了...");  
  50.                 } else {  
  51.                     textView.setText(result);  
  52.                 }  
  53.                 dialog.dismiss();  
  54.                 super.onPostExecute(result);  
  55.             }  
  56.  
  57.         }.execute();  
  58.     }  
  59.  
  60. }  

(2

  1. package com.example.gpsdemo.util;  
  2.  
  3. import java.io.BufferedReader;  
  4. import java.io.InputStreamReader;  
  5.  
  6. import org.apache.http.HttpEntity;  
  7. import org.apache.http.HttpHost;  
  8. import org.apache.http.HttpResponse;  
  9. import org.apache.http.client.HttpClient;  
  10. import org.apache.http.client.methods.HttpPost;  
  11. import org.apache.http.conn.params.ConnRouteParams;  
  12. import org.apache.http.entity.StringEntity;  
  13. import org.apache.http.impl.client.DefaultHttpClient;  
  14. import org.apache.http.params.HttpConnectionParams;  
  15. import org.json.JSONArray;  
  16. import org.json.JSONObject;  
  17.  
  18. import android.content.Context;  
  19. import android.database.Cursor;  
  20. import android.net.ConnectivityManager;  
  21. import android.net.NetworkInfo.State;  
  22. import android.net.Uri;  
  23. import android.net.wifi.WifiManager;  
  24. import android.telephony.TelephonyManager;  
  25. import android.telephony.gsm.GsmCellLocation;  
  26. import android.util.Log;  
  27.  
  28. /**  
  29.  * ******************************************<br>  
  30.  * 描述::GPS信息获取<br>  
  31.  * @version 2.0<br>  
  32.  ********************************************   
  33.  */ 
  34. public class GPSLocation {  
  35.     private static int postType = -1;  
  36.     public static final int DO_3G = 0;  
  37.     public static final int DO_WIFI = 1;  
  38.     public static final int NO_CONNECTION = 2;  
  39.  
  40.     /**  
  41.      * 网络方式检查  
  42.      */ 
  43.     private static int netCheck(Context context) {  
  44.         ConnectivityManager conMan = (ConnectivityManager) context  
  45.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
  46.         State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)  
  47.                 .getState();  
  48.         State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)  
  49.                 .getState();  
  50.         if (wifi.equals(State.CONNECTED)) {  
  51.             return DO_WIFI;  
  52.         } else if (mobile.equals(State.CONNECTED)) {  
  53.             return DO_3G;  
  54.         } else {  
  55.             return NO_CONNECTION;  
  56.         }  
  57.     }  
  58.  
  59.     /**  
  60.      * 获取WifiManager获取信息  
  61.      */ 
  62.     private static JSONObject getInfoByWifiManager(Context context)  
  63.             throws Exception {  
  64.         JSONObject holder = new JSONObject();  
  65.         holder.put("version""1.1.0");  
  66.         holder.put("host""maps.google.com");  
  67.         holder.put("address_language""zh_CN");  
  68.         holder.put("request_address"true);  
  69.  
  70.         WifiManager wifiManager = (WifiManager) context  
  71.                 .getSystemService(Context.WIFI_SERVICE);  
  72.  
  73.         if (wifiManager.getConnectionInfo().getBSSID() == null) {  
  74.             throw new RuntimeException("bssid is null");  
  75.         }  
  76.  
  77.         JSONArray array = new JSONArray();  
  78.         JSONObject data = new JSONObject();  
  79.         data.put("mac_address", wifiManager.getConnectionInfo().getBSSID());  
  80.         data.put("signal_strength"8);  
  81.         data.put("age"0);  
  82.         array.put(data);  
  83.         holder.put("wifi_towers", array);  
  84.         return holder;  
  85.     }  
  86.  
  87.     /**  
  88.      * 获取TelephoneManager获取信息  
  89.      */ 
  90.     private static JSONObject getInfoByTelephoneManager(Context context)  
  91.             throws Exception {  
  92.         JSONObject holder = new JSONObject();  
  93.         holder.put("version""1.1.0");  
  94.         holder.put("host""maps.google.com");  
  95.         holder.put("address_language""zh_CN");  
  96.         holder.put("request_address"true);  
  97.         TelephonyManager tm = (TelephonyManager) context  
  98.                 .getSystemService(Context.TELEPHONY_SERVICE);  
  99.         GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation();  
  100.         int cid = gcl.getCid();  
  101.         int lac = gcl.getLac();  
  102.         int mcc = Integer.valueOf(tm.getNetworkOperator().substring(03));  
  103.         int mnc = Integer.valueOf(tm.getNetworkOperator().substring(35));  
  104.         JSONArray array = new JSONArray();  
  105.         JSONObject data = new JSONObject();  
  106.         data.put("cell_id", cid);  
  107.         data.put("location_area_code", lac);  
  108.         data.put("mobile_country_code", mcc);  
  109.         data.put("mobile_network_code", mnc);  
  110.         array.put(data);  
  111.         holder.put("cell_towers", array);  
  112.         return holder;  
  113.     }  
  114.  
  115.     /**  
  116.      * 通过wifi获取GPS信息  
  117.      */ 
  118.     private static HttpResponse connectionForGPS(Context context)  
  119.             throws Exception {  
  120.         HttpResponse httpResponse = null;  
  121.         postType = netCheck(context);  
  122.         if (postType == NO_CONNECTION) {  
  123.             return null;  
  124.         } else {  
  125.             if (postType == DO_WIFI) {  
  126.                 if ((httpResponse = doOrdinary(context,  
  127.                         getInfoByWifiManager(context))) != null) {  
  128.                     return httpResponse;  
  129.                 } else if ((httpResponse = doAPN(context,  
  130.                         getInfoByWifiManager(context))) != null) {  
  131.                     return httpResponse;  
  132.                 } else if ((httpResponse = doOrdinary(context,  
  133.                         getInfoByTelephoneManager(context))) != null) {  
  134.                     return httpResponse;  
  135.                 } else if ((httpResponse = doAPN(context,  
  136.                         getInfoByTelephoneManager(context))) != null) {  
  137.                     return httpResponse;  
  138.                 }  
  139.             }  
  140.             if (postType == DO_3G) {  
  141.                 if ((httpResponse = doOrdinary(context,  
  142.                         getInfoByTelephoneManager(context))) != null) {  
  143.                     return httpResponse;  
  144.                 } else if ((httpResponse = doAPN(context,  
  145.                         getInfoByTelephoneManager(context))) != null) {  
  146.                     return httpResponse;  
  147.                 }  
  148.             }  
  149.             return null;  
  150.         }  
  151.     }  
  152.  
  153.     /**  
  154.      * 通过普通方式定位  
  155.      */ 
  156.     private static HttpResponse doOrdinary(Context context, JSONObject holder) {  
  157.         HttpResponse response = null;  
  158.         try {  
  159.             HttpClient httpClient = new DefaultHttpClient();  
  160.             HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),  
  161.                     20 * 1000);  
  162.             HttpConnectionParams  
  163.                     .setSoTimeout(httpClient.getParams(), 20 * 1000);  
  164.             HttpPost post = new HttpPost("http://74.125.71.147/loc/json");  
  165.             StringEntity se = new StringEntity(holder.toString());  
  166.             post.setEntity(se);  
  167.             response = httpClient.execute(post);  
  168.         } catch (Exception e) {  
  169.             e.printStackTrace();  
  170.             return null;  
  171.         }  
  172.         return response;  
  173.     }  
  174.  
  175.     /**  
  176.      * 通过基站定位  
  177.      */ 
  178.     private static HttpResponse doAPN(Context context, JSONObject holder) {  
  179.         HttpResponse response = null;  
  180.         try {  
  181.             HttpClient httpClient = new DefaultHttpClient();  
  182.             HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),  
  183.                     20 * 1000);  
  184.             HttpConnectionParams  
  185.                     .setSoTimeout(httpClient.getParams(), 20 * 1000);  
  186.             HttpPost post = new HttpPost("http://74.125.71.147/loc/json");  
  187.             // 设置代理  
  188.             Uri uri = Uri.parse("content://telephony/carriers/preferapn"); // 获取当前正在使用的APN接入点  
  189.             Cursor mCursor = context.getContentResolver().query(uri, null,  
  190.                     nullnullnull);  
  191.             if (mCursor != null) {  
  192.                 if (mCursor.moveToFirst()) {  
  193.                     String proxyStr = mCursor.getString(mCursor  
  194.                             .getColumnIndex("proxy"));  
  195.                     if (proxyStr != null && proxyStr.trim().length() > 0) {  
  196.                         HttpHost proxy = new HttpHost(proxyStr, 80);  
  197.                         httpClient.getParams().setParameter(  
  198.                                 ConnRouteParams.DEFAULT_PROXY, proxy);  
  199.                     }  
  200.                 }  
  201.             }  
  202.             StringEntity se = new StringEntity(holder.toString());  
  203.             post.setEntity(se);  
  204.             response = httpClient.execute(post);  
  205.         } catch (Exception e) {  
  206.             e.printStackTrace();  
  207.             return null;  
  208.         }  
  209.         return response;  
  210.     }  
  211.  
  212.     /**  
  213.      * GPS信息解析  
  214.      */ 
  215.     public static LMLocation getGPSInfo(Context context) throws Exception {  
  216.         HttpResponse response = connectionForGPS(context);  
  217.         if (response == null) {  
  218.             Log.d("GPSLocation""response == null");  
  219.             return null;  
  220.         }  
  221.         LMLocation location = null;  
  222.         if (response.getStatusLine().getStatusCode() == 200) {  
  223.             location = new LMLocation();  
  224.             HttpEntity entity = response.getEntity();  
  225.             BufferedReader br;  
  226.             try {  
  227.                 br = new BufferedReader(new InputStreamReader(  
  228.                         entity.getContent()));  
  229.                 StringBuffer sb = new StringBuffer();  
  230.                 String result = br.readLine();  
  231.                 while (result != null) {  
  232.                     sb.append(result);  
  233.                     result = br.readLine();  
  234.                 }  
  235.                 JSONObject json = new JSONObject(sb.toString());  
  236.                 JSONObject lca = json.getJSONObject("location");  
  237.  
  238.                 location.setAccess_token(json.getString("access_token"));  
  239.                 if (lca != null) {  
  240.                     if (lca.has("accuracy"))  
  241.                         location.setAccuracy(lca.getString("accuracy"));  
  242.                     if (lca.has("longitude"))  
  243.                         location.setLatitude(lca.getDouble("longitude"));  
  244.                     if (lca.has("latitude"))  
  245.                         location.setLongitude(lca.getDouble("latitude"));  
  246.                     if (lca.has("address")) {  
  247.                         JSONObject address = lca.getJSONObject("address");  
  248.                         if (address != null) {  
  249.                             if (address.has("region"))  
  250.                                 location.setRegion(address.getString("region"));  
  251.                             if (address.has("street_number"))  
  252.                                 location.setStreet_number(address  
  253.                                         .getString("street_number"));  
  254.                             if (address.has("country_code"))  
  255.                                 location.setCountry_code(address  
  256.                                         .getString("country_code"));  
  257.                             if (address.has("street"))  
  258.                                 location.setStreet(address.getString("street"));  
  259.                             if (address.has("city"))  
  260.                                 location.setCity(address.getString("city"));  
  261.                             if (address.has("country"))  
  262.                                 location.setCountry(address  
  263.                                         .getString("country"));  
  264.                         }  
  265.                     }  
  266.                 }  
  267.             } catch (Exception e) {  
  268.                 e.printStackTrace();  
  269.                 location = null;  
  270.             }  
  271.         }  
  272.         return location;  
  273.     }  
  274.  
  275. }  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值