1. 程式人生 > >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

package com.example.gpsdemo;  
 
import com.example.gpsdemo.util.GetLocation;  
import com.example.gpsdemo.util.LMLocation;  
 
import android.app.Activity;  
import android.app.AlertDialog;  
import android.app.ProgressDialog;  
import android.os.Bundle;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
import android.widget.TextView;  
 
public class MainActivity extends Activity {  
    LMLocation lmLocation;  
    TextView textView;  
    public MainActivity instance;  
    private AlertDialog dialog;  
    @Override
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        textView = (TextView) findViewById(R.id.textView2);  
        instance = this;  
        dialog = new ProgressDialog(MainActivity.this);  
        dialog.setTitle("請稍等...");  
        dialog.setMessage("正在定位...");  
        Button button = (Button) findViewById(R.id.button1);  
        button.setOnClickListener(new OnClickListener() {  
 
            @Override
            public void onClick(View v) {  
                // TODO Auto-generated method stub
                new GetLocation(dialog, textView, instance).DisplayLocation();  
            }  
        });  
 
    }  
 
}  

2.與MainActivity對應的佈局
<xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
     
       <android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:padding="@dimen/padding_medium"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />
 
     
        <android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/textView2"
        android:layout_marginRight="52dp"
        android:text="定位" />

3.AndroidManifest.xml
  1. package="com.example.gpsdemo"
  2.     android:versionCode="1"
  3.     android:versionName="1.0" >
  4.     <uses-sdk< li="">
  5.         android:minSdkVersion="8"
  6.         android:targetSdkVersion="15" />
  7.     <application< li="">
  8.         android:icon="@drawable/ic_launcher"
  9.         android:label="@string/app_name"
  10.         android:theme="@style/AppTheme" >
  11.         <activity< li="">
  12.             android:name=".MainActivity"
  13.             android:label="@string/title_activity_main" >
4.工具類兩個:(1)
package com.example.gpsdemo.util;  
 
import android.app.AlertDialog;  
import android.content.Context;  
import android.os.AsyncTask;  
import android.util.Log;  
import android.widget.TextView;  
 
public class GetLocation {  
    AlertDialog dialog;  
    TextView textView;  
    Context context;  
 
    public GetLocation(AlertDialog dialog, TextView textView, Context context) {  
        this.dialog = dialog;  
        this.textView = textView;  
        this.context = context;  
 
    }  
 
    public void DisplayLocation() {  
        new AsyncTask() {  
 
            @Override
            protected String doInBackground=\'#\'"  
                LMLocation location = null;  
                try {  
                    location = new GPSLocation().getGPSInfo(context);  
                } catch (Exception e) {  
                    // TODO Auto-generated catch block
                    e.printStackTrace();  
                }  
                if (location == null)  
                    return null;  
                Log.d("debug", location.toString());  
                return location.toString();  
 
            }  
 
            @Override
            protected void onPreExecute() {  
                dialog.show();  
                super.onPreExecute();  
            }  
 
            @Override
            protected void onPostExecute(String result) {  
                if (result == null) {  
                    textView.setText("定位失敗了...");  
                } else {  
                    textView.setText(result);  
                }  
                dialog.dismiss();  
                super.onPostExecute(result);  
            }  
 
        }.execute();  
    }  
 
}  

2.
package com.example.gpsdemo.util;  
 
import java.io.BufferedReader;  
import java.io.InputStreamReader;  
 
import org.apache.http.HttpEntity;  
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.JSONArray;  
import org.json.JSONObject;  
 
import android.content.Context;  
import android.database.Cursor;  
import android.net.ConnectivityManager;  
import android.net.NetworkInfo.State;  
import android.net.Uri;  
import android.net.wifi.WifiManager;  
import android.telephony.TelephonyManager;  
import android.telephony.gsm.GsmCellLocation;  
import android.util.Log;  
 
/**
 * ******************************************
 * 描述::GPS資訊獲取
 * @version 2.0
 ******************************************** 
 */
public class GPSLocation {  
    private static int postType = -1;  
    public static final int DO_3G = 0;  
    public static final int DO_WIFI = 1;  
    public static final int NO_CONNECTION = 2;  
 
    /**
     * 網路方式檢查
     */
    private static int netCheck(Context context) {  
        ConnectivityManager conMan = (ConnectivityManager) context  
                .getSystemService(Context.CONNECTIVITY_SERVICE);  
        State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)  
                .getState();  
        State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)  
                .getState();  
        if (wifi.equals(State.CONNECTED)) {  
            return DO_WIFI;  
        } else if (mobile.equals(State.CONNECTED)) {  
            return DO_3G;  
        } else {  
            return NO_CONNECTION;  
        }  
    }  
 
    /**
     * 獲取WifiManager獲取資訊
     */
    private static JSONObject getInfoByWifiManager(Context context)  
            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);  
 
        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;  
    }  
 
    /**
     * 獲取TelephoneManager獲取資訊
     */
    private static JSONObject getInfoByTelephoneManager(Context context)  
            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);  
        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;  
    }  
 
    /**
     * 通過wifi獲取GPS資訊
     */
    private static HttpResponse connectionForGPS(Context context)  
            throws Exception {  
        HttpResponse httpResponse = null;  
        postType = netCheck(context);  
        if (postType == NO_CONNECTION) {  
            return null;  
        } else {  
            if (postType == DO_WIFI) {  
                if ((httpResponse = doOrdinary(context,  
                        getInfoByWifiManager(context))) != null) {  
                    return httpResponse;  
                } else if ((httpResponse = doAPN(context,  
                        getInfoByWifiManager(context))) != null) {  
                    return httpResponse;  
                } else if ((httpResponse = doOrdinary(context,  
                        getInfoByTelephoneManager(context))) != null) {  
                    return httpResponse;  
                } else if ((httpResponse = doAPN(context,  
                        getInfoByTelephoneManager(context))) != null) {  
                    return httpResponse;  
                }  
            }  
            if (postType == DO_3G) {  
                if ((httpResponse = doOrdinary(context,  
                        getInfoByTelephoneManager(context))) != null) {  
                    return httpResponse;  
                } else if ((httpResponse = doAPN(context,  
                        getInfoByTelephoneManager(context))) != null) {  
                    return httpResponse;  
                }  
            }  
            return null;  
        }  
    }  
 
    /**
     * 通過普通方式定位
     */
    private static HttpResponse doOrdinary(Context context, JSONObject holder) {  
        HttpResponse response = null;  
        try {  
            HttpClient httpClient = new DefaultHttpClient();  
            HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),  
                    20 * 1000);  
            HttpConnectionParams  
                    .setSoTimeout(httpClient.getParams(), 20 * 1000);  
            HttpPost post = new HttpPost("http://74.125.71.147/loc/json");  
            StringEntity se = new StringEntity(holder.toString());  
            post.setEntity(se);  
            response = httpClient.execute(post);  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
        return response;  
    }  
 
    /**
     * 通過基站定位
     */
    private static HttpResponse doAPN(Context context, JSONObject holder) {  
        HttpResponse response = null;  
        try {  
            HttpClient httpClient = new DefaultHttpClient();  
            HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),  
                    20 * 1000);  
            HttpConnectionParams  
                    .setSoTimeout(httpClient.getParams(), 20 * 1000);  
            HttpPost post = new HttpPost("http://74.125.71.147/loc/json");  
            // 設定代理
            Uri uri = Uri.parse("content://telephony/carriers/preferapn"); // 獲取當前正在使用的APN接入點  
            Cursor mCursor = context.getContentResolver().query(uri, null,  
                    null, null, null);  
            if (mCursor != null) {  
                if (mCursor.moveToFirst()) {  
                    String proxyStr = mCursor.getString(mCursor  
                            .getColumnIndex("proxy"));  
                    if (proxyStr != null && proxyStr.trim().length() > 0) {  
                        HttpHost proxy = new HttpHost(proxyStr, 80);  
                        httpClient.getParams().setParameter(  
                                ConnRouteParams.DEFAULT_PROXY, proxy);  
                    }  
                }  
            }  
            StringEntity se = new StringEntity(holder.toString());  
            post.setEntity(se);  
            response = httpClient.execute(post);  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
        return response;  
    }  
 
    /**
     * GPS資訊解析
     */
    public static LMLocation getGPSInfo(Context context) throws Exception {  
        HttpResponse response = connectionForGPS(context);  
        if (response == null) {  
            Log.d("GPSLocation", "response == null");  
            return null;  
        }  
        LMLocation location = null;  
        if (response.getStatusLine().getStatusCode() == 200) {  
            location = new LMLocation();  
            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.setAccess_token(json.getString("access_token"));  
                if (lca != null) {  
                    if (lca.has("accuracy"))  
                        location.setAccuracy(lca.getString("accuracy"));  
                    if (lca.has("longitude"))  
                        location.setLatitude(lca.getDouble("longitude"));  
                    if (lca.has("latitude"))  
                        location.setLongitude(lca.getDouble("latitude"));  
                    if (lca.has("address")) {  
                        JSONObject address = lca.getJSONObject("address");  
                        if (address != null) {  
                            if (address.has("region"))  
                                location.setRegion(address.getString("region"));  
                            if (address.has("street_number"))  
                                location.setStreet_number(address  
                                        .getString("street_number"));  
                            if (address.has("country_code"))  
                                location.setCountry_code(address  
                                        .getString("country_code"));  
                            if (address.has("street"))  
                                location.setStreet(address.getString("street"));  
                            if (address.has("city"))  
                                location.setCity(address.getString("city"));  
                            if (address.has("country"))  
                                location.setCountry(address  
                                        .getString("country"));  
                        }  
                    }  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
                location = null;  
            }  
        }  
        return location;  
    }  
 
}  
)