Location in Android: Part 3 (FINISH)

前文中所提到的Cell-ID和WI-FI定位方法,在Android官方文档《Obtaining User Location》中并入Network Location Provider一类,与GPS地位等同。前文中介绍的方法虽然可行,但是需要开发者处理比较多的数据。实际上,不必这么麻烦,还有更简单的方法,android.location中的LocationManager封装了地理位置信息的接口,提供了GPS_PROVIDER和NETWORK_PROVIDER等。

如果开发的应用需要高精确性,那么可使用GPS_PROVIDER,但这也意味着应用无法在室内使用,待机时间缩短,响应时间稍长等问题;如果开发的应用需要快速反应,对精度要求不怎么高,并且要尽可能节省电量,那么使用NETWORK_PROVIDER是不错的选择。这里提一下,还有一个PASSIVE_PROVIDER,在实际应用中较少使用。

提到GPS(Global Positioning System),那就顺便说说题外话,由于GPS前身来自于美国军方,后来“军转民”。尽管不收费,但是出于各自国家战略安全和商业利益考量,欧盟发起了伽利略定位系统(Gallileo Postionting System),俄罗斯建立了格洛纳斯(GLONASS),中国也开发了北斗卫星导航系统。尽管呈现出竞争格局,但是目前在非军用移动设备上,–例如手机、MID等,GPS占据了巨大的市场份额。目前来看,Android对GPS的支持还是相当给力,不过也希望未来能够在Android上收到来自北斗的信号。

言归正传,如下代码就是设置从Network中获取位置:

LocationManager mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocLis);

上面的代码需要对应的权限:android.permission.ACCESS_COARSE_LOCATION,同样,如果是GPS_PROVIDER,则需要权限android.permission.ACCESS_FINE_LOCATION。如果代码里使用了两个PROVIDER,则只需要一个权限即可:android.permission.ACCESS_FINE_LOCATION。

以下是整个过程的代码,由于目的只是技术验证,因此未做效率、健壮性等考虑,不过这并不妨碍我们对比四种获取locaiton方式的差异,其中的优劣由读者自行评判:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
public class DemoActivity extends Activity {
 
    private static final String TAG = "DemoActivity";
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
 
    public void onRequestLocation(View view) {
        switch (view.getId()){
        case R.id.gpsBtn:
            Log.d(TAG, "GPS button is clicked");
            requestGPSLocation();
            break;
        case R.id.telBtn:
            Log.d(TAG, "CellID button is clicked");
            requestTelLocation();
            break;
        case R.id.wifiBtn:
            Log.d(TAG, "WI-FI button is clicked");
            requestWIFILocation();
            break;
        case R.id.netBtn:
            Log.d(TAG, "Network button is clicked");
            requestNetworkLocation();
            break;
        }
    }
 
    private void requestTelLocation() {
        TelephonyManager mTelMan = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        // MCC+MNC. Unreliable on CDMA networks
        String operator = mTelMan.getNetworkOperator();
        String mcc = operator.substring(0, 3);
        String mnc = operator.substring(3);
 
        GsmCellLocation location = (GsmCellLocation) mTelMan.getCellLocation();
        int cid = location.getCid();
        int lac = location.getLac();
 
        JSONObject tower = new JSONObject();
        try {
            tower.put("cell_id", cid);
            tower.put("location_area_code", lac);
            tower.put("mobile_country_code", mcc);
            tower.put("mobile_network_code", mnc);
        } catch (JSONException e) {
            Log.e(TAG, "call JSONObject's put failed", e);
        }
 
        JSONArray array = new JSONArray();
        array.put(tower);
 
        List<NeighboringCellInfo> list = mTelMan.getNeighboringCellInfo();
        Iterator<NeighboringCellInfo> iter = list.iterator();
        NeighboringCellInfo cellInfo;
        JSONObject tempTower;
        while (iter.hasNext()) {
            cellInfo = iter.next();
            tempTower = new JSONObject();
            try {
                tempTower.put("cell_id", cellInfo.getCid());
                tempTower.put("location_area_code", cellInfo.getLac());
                tempTower.put("mobile_country_code", mcc);
                tempTower.put("mobile_network_code", mnc);
            } catch (JSONException e) {
                Log.e(TAG, "call JSONObject's put failed", e);
            }
            array.put(tempTower);
        }
 
        JSONObject object = createJSONObject("cell_towers", array);
        requestLocation(object);
    }
 
    private void requestWIFILocation() {
        WifiManager wifiMan = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifiMan.getConnectionInfo();
        String mac = info.getMacAddress();
        String ssid = info.getSSID();
 
        JSONObject wifi = new JSONObject();
        try {
            wifi.put("mac_address", mac);
            wifi.put("ssid", ssid);
        } catch (JSONException e) {
            e.printStackTrace();
        }
 
        JSONArray array = new JSONArray();
        array.put(wifi);
 
        JSONObject object = createJSONObject("wifi_towers", array);
        requestLocation(object);
    }
 
    private void requestLocation(JSONObject object) {
        Log.d(TAG, "requestLocation: " + object.toString());
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.google.com/loc/json");
        try {
            StringEntity entity = new StringEntity(object.toString());
            post.setEntity(entity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
 
        try {
            HttpResponse resp = client.execute(post);
            HttpEntity entity = resp.getEntity();
            BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
            StringBuffer buffer = new StringBuffer();
            String result = br.readLine();
            while (result != null) {
                buffer.append(result);
                result = br.readLine();
            }
 
            Log.d(TAG, buffer.toString());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    private JSONObject createJSONObject(String arrayName, JSONArray array) {
        JSONObject object = new JSONObject();
        try {
            object.put("version", "1.1.0");
            object.put("host", "maps.google.com");
            object.put(arrayName, array);
        } catch (JSONException e) {
            Log.e(TAG, "call JSONObject's put failed", e);
        }
        return object;
    }
 
    private void requestGPSLocation() {
        LocationManager mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 * 60, 100, mLocLis);
    }
 
    private void requestNetworkLocation() {
        LocationManager mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000 * 60, 100, mLocLis);
    }
 
    private LocationListener mLocLis = new LocationListener() {
 
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.d(TAG, "onStatusChanged, provider = " + provider);
        }
 
        @Override
        public void onProviderEnabled(String provider) {
            Log.d(TAG, "onProviderEnabled, provider = " + provider);
        }
 
        @Override
        public void onProviderDisabled(String provider) {
            Log.d(TAG, "onProviderDisabled, provider = " + provider);
        }
 
        @Override
        public void onLocationChanged(Location location) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            Log.d(TAG, "latitude: " + latitude + ", longitude: " + longitude);
        }
    };
}

1 Comment

[…] 原文链接:http://www.poemcode.net/2011/01/location-in-android-3/ >>> 进入[Android2D游戏开发]主题文章列表 转载编辑: Fgamers 转载地址:http://disanji.net/2011/03/11/location-in-android-part-3/ 分享到 | blog comments powered by Disqus /* […]

Leave a comment

Your comment