Android 定位

jopen 11年前發布 | 19K 次閱讀 Android Android開發 移動開發

先從GPS模塊獲取,再從wifi/gprs模塊中獲取,最終從蜂窩網中獲取設備位置。

import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.io.UnsupportedEncodingException;  
import java.net.MalformedURLException;  
import java.net.URL;  
import java.net.URLConnection;  

import org.apache.http.HttpEntity;  
import org.apache.http.HttpResponse;  
import org.apache.http.client.ClientProtocolException;  
import org.apache.http.client.methods.HttpPost;  
import org.apache.http.entity.StringEntity;  
import org.apache.http.impl.client.DefaultHttpClient;  
import org.json.JSONArray;  
import org.json.JSONException;  
import org.json.JSONObject;  
import org.json.JSONTokener;  

import android.content.Context;  
import android.location.Location;  
import android.location.LocationManager;  
import android.telephony.TelephonyManager;  
import android.telephony.gsm.GsmCellLocation;  

import com.example.pickride.PickrideApplication;  

public class LocationTools {  
    public static String getLocation() {  
        return getDeviceAddressbyGeoPoint();  
    }  

    /** 
     * 獲取地址 
     *  
     * @return 
     */  
    private static String getDeviceAddressbyGeoPoint() {  
        // 自經緯度取得地址  
        LocationManager locationManager = (LocationManager) PickrideApplication  
                .getAppContext().getSystemService(Context.LOCATION_SERVICE);  
        Location location = locationManager  
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);  

        if (location == null) {  
            location = locationManager  
                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);// 如果gps取不到就取網絡的  
        }  

        // Log.d("H3c",  
        // "k:" + location.getLatitude() + "-" + location.getLongitude());  

        if (location == null) {  
            String locaStr = getLocationByGSMCell();// 如果wifi網絡無法獲取就獲取基站的  
            if (locaStr != null) {  
                return locaStr;  
            }  
        }  

        if (location == null) {  
            return "";// 無法獲取該位置  
        }  

        String add = GetAddr(String.valueOf(location.getLatitude()),  
                String.valueOf(location.getLongitude()));  

        if (add != null) {  
            return add;  
        }  

        return location.getLatitude() + "-" + location.getLongitude();  
    }  

    /** 
     * 根據經緯度反向解析地址,有時需要多嘗試幾次 
     * 注意:(摘自:http://code.google.com/intl/zh-CN/apis/maps/faq.html 
     * 提交的地址解析請求次數是否有限制?) 如果在 24 小時時段內收到來自一個 IP 地址超過 2500 個地址解析請求, 或從一個 IP 
     * 地址提交的地址解析請求速率過快,Google 地圖 API 編碼器將用 620 狀態代碼開始響應。 如果地址解析器的使用仍然過多,則從該 IP 
     * 地址對 Google 地圖 API 地址解析器的訪問可能被永久阻止。 
     *  
     * @param latitude 
     *            緯度 
     * @param longitude 
     *            經度 
     * @return 
     */  
    private static String GetAddr(String latitude, String longitude) {  
        String addr = "";  
        // 也可以是http://maps.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s,不過解析出來的是英文地址  
        // 密鑰可以隨便寫一個key=abc  
        // output=csv,也可以是xml或json,不過使用csv返回的數據最簡潔方便解析  
        String url = String.format(  
                "http://ditu.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s",  
                latitude, longitude);  
        URL myURL = null;  
        URLConnection httpsConn = null;  
        try {  
            myURL = new URL(url);  
        } catch (MalformedURLException e) {  
            e.printStackTrace();  
            return null;  
        }  

        try {  
            httpsConn = (URLConnection) myURL.openConnection();  
            if (httpsConn != null) {  
                InputStreamReader insr = new InputStreamReader(  
                        httpsConn.getInputStream(), "UTF-8");  
                BufferedReader br = new BufferedReader(insr);  
                String data = null;  
                if ((data = br.readLine()) != null) {  
                    String[] retList = data.split(",");  
                    if (retList.length > 2 && ("200".equals(retList[0]))) {  
                        addr = retList[2];  
                        addr = addr.replace("\"", "");  
                        addr = addr.split(" ")[0];// 只獲得地址,否則是地址+郵編  
                    } else {  
                        addr = "";  
                    }  
                }  
                insr.close();  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
            return null;  
        }  
        return addr;  
    }  

    private static String getLocationByGSMCell() {  
        TelephonyManager tm = (TelephonyManager) PickrideApplication  
                .getAppContext().getSystemService(Context.TELEPHONY_SERVICE);  
        GsmCellLocation gsmCell = (GsmCellLocation) tm.getCellLocation();  
        int cid = gsmCell.getCid();  
        int lac = gsmCell.getLac();  
        String netOperator = tm.getNetworkOperator();  
        int mcc = Integer.valueOf(netOperator.substring(0, 3));  
        int mnc = Integer.valueOf(netOperator.substring(3, 5));  
        JSONObject holder = new JSONObject();  
        JSONArray array = new JSONArray();  
        JSONObject data = new JSONObject();  
        try {  
            holder.put("version", "1.1.0");  
            holder.put("host", "maps.google.com");  
            holder.put("address_language", "zh_CN");  
            holder.put("request_address", true);  
            holder.put("radio_type", "gsm");  
            holder.put("carrier", "HTC");  
            data.put("cell_id", cid);  
            data.put("location_area_code", lac);  
            data.put("mobile_countyr_code", mcc);  
            data.put("mobile_network_code", mnc);  
            array.put(data);  
            holder.put("cell_towers", array);  
        } catch (JSONException e) {  
            e.printStackTrace();  
        }  
        DefaultHttpClient client = new DefaultHttpClient();  
        HttpPost httpPost = new HttpPost("http://www.google.com/loc/json");  
        StringEntity stringEntity = null;  
        try {  
            stringEntity = new StringEntity(holder.toString());  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        httpPost.setEntity(stringEntity);  
        HttpResponse httpResponse = null;  
        try {  
            httpResponse = client.execute(httpPost);  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        HttpEntity httpEntity = httpResponse.getEntity();  
        InputStream is = null;  
        try {  
            is = httpEntity.getContent();  
        } catch (IllegalStateException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        InputStreamReader isr = new InputStreamReader(is);  
        BufferedReader reader = new BufferedReader(isr);  
        StringBuffer stringBuffer = new StringBuffer();  
        try {  
            String result = "";  
            while ((result = reader.readLine()) != null) {  
                stringBuffer.append(result);  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        String location = stringBuffer.toString();  
        try {  
            JSONTokener jsonParser = new JSONTokener(location);  
            JSONObject person = (JSONObject) jsonParser.nextValue();  
            JSONObject oj1 = person.getJSONObject("location");  
            JSONObject oj2 = oj1.getJSONObject("address");  
            String region = oj2.getString("region");  
            String city = oj2.getString("city");  
            String street = oj2.getString("street");  
            return region + city + street;  
        } catch (JSONException e) {  
            e.printStackTrace();  
        }  
        return null;  
    }  
}  

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!