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

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. import com.example.gpsdemo.util.GetLocation;
  3. import com.example.gpsdemo.util.LMLocation;
  4. import android.app.Activity;
  5. import android.app.AlertDialog;
  6. import android.app.ProgressDialog;
  7. import android.os.Bundle;
  8. import android.view.View;
  9. import android.view.View.OnClickListener;
  10. import android.widget.Button;
  11. import android.widget.TextView;
  12. public class MainActivity extends Activity {
  13.     LMLocation lmLocation;
  14.     TextView textView;
  15.     public MainActivity instance;
  16.     private AlertDialog dialog;
  17.     @Override
  18.     public void onCreate(Bundle savedInstanceState) {
  19.         super.onCreate(savedInstanceState);
  20.         setContentView(R.layout.activity_main);
  21.         textView = (TextView) findViewById(R.id.textView2);
  22.         instance = this;
  23.         dialog = new ProgressDialog(MainActivity.this);
  24.         dialog.setTitle(“请稍等…”);
  25.         dialog.setMessage(“正在定位…”);
  26.         Button button = (Button) findViewById(R.id.button1);
  27.         button.setOnClickListener(new OnClickListener() {
  28.             @Override
  29.             public void onClick(View v) {
  30.                 // TODO Auto-generated method stub
  31.                 new GetLocation(dialog, textView, instance).DisplayLocation();
  32.             }
  33.         });
  34.     }
  35. }
 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.     <TextView
  6.         android:id=“@+id/textView2”
  7.         android:layout_width=“wrap_content”
  8.         android:layout_height=“wrap_content”
  9.         android:layout_centerHorizontal=“true”
  10.         android:layout_centerVertical=“true”
  11.         android:padding=“@dimen/padding_medium”
  12.         android:text=“@string/hello_world”
  13.         tools:context=“.MainActivity” />
  14.     <Button
  15.         android:id=“@+id/button1”
  16.         android:layout_width=“wrap_content”
  17.         android:layout_height=“wrap_content”
  18.         android:layout_alignParentTop=“true”
  19.         android:layout_alignRight=“@+id/textView2”
  20.         android:layout_marginRight=“52dp”
  21.         android:text=“定位” />
  22. </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.     <uses-sdk
  6.         android:minSdkVersion=“8”
  7.         android:targetSdkVersion=“15” />
  8.     <application
  9.         android:icon=“@drawable/ic_launcher”
  10.         android:label=“@string/app_name”
  11.         android:theme=“@style/AppTheme” >
  12.         <activity
  13.             android:name=“.MainActivity”
  14.             android:label=“@string/title_activity_main” >
  15.             <intent-filter>
  16.                 <action android:name=“android.intent.action.MAIN” />
  17.                 <category android:name=“android.intent.category.LAUNCHER” />
  18.             </intent-filter>
  19.         </activity>
  20.     </application>
  21.       <!– 获取地理位置权限 –>
  22.      <uses-permission android:name=“android.permission.INTERNET” />
  23.     <uses-permission android:name=“android.permission.WRITE_EXTERNAL_STORAGE” />
  24.     <uses-permission android:name=“android.permission.ACCESS_FINE_LOCATION” />
  25.     <uses-permission android:name=“android.permission.ACCESS_NETWORK_STATE” />
  26.     <uses-permission android:name=“android.permission.ACCESS_WIFI_STATE” />
  27.     <uses-permission android:name=“android.permission.READ_CONTACTS”></uses-permission>
  28.     <uses-permission android:name=“android.permission.READ_PHONE_STATE”></uses-permission>
  29. </manif

 

 

4.工具类两个:(1)

 

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

(2

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

)

 

转自:http://www.verydemo.com/demo_c128_i63026.html

标签

发表评论

Comment List(3)