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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.server.location;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Address;
import android.location.Country;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Slog;
/**
* This class detects which country the user currently is in through the enabled
* location providers and the GeoCoder
* <p>
* Use {@link #detectCountry} to start querying. If the location can not be
* resolved within the given time, the last known location will be used to get
* the user country through the GeoCoder. The IllegalStateException will be
* thrown if there is a ongoing query.
* <p>
* The current query can be stopped by {@link #stop()}
*
* @hide
*/
public class LocationBasedCountryDetector extends CountryDetectorBase {
private final static String TAG = "LocationBasedCountryDetector";
private final static long QUERY_LOCATION_TIMEOUT = 1000 * 60 * 5; // 5 mins
/**
* Used for canceling location query
*/
protected Timer mTimer;
/**
* The thread to query the country from the GeoCoder.
*/
protected Thread mQueryThread;
protected List<LocationListener> mLocationListeners;
private LocationManager mLocationManager;
private List<String> mEnabledProviders;
public LocationBasedCountryDetector(Context ctx) {
super(ctx);
mLocationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
}
/**
* @return the ISO 3166-1 two letters country code from the location
*/
protected String getCountryFromLocation(Location location) {
String country = null;
Geocoder geoCoder = new Geocoder(mContext);
try {
List<Address> addresses = geoCoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1);
if (addresses != null && addresses.size() > 0) {
country = addresses.get(0).getCountryCode();
}
} catch (IOException e) {
Slog.w(TAG, "Exception occurs when getting country from location");
}
return country;
}
/**
* Register the listeners with the location providers
*/
protected void registerEnabledProviders(List<LocationListener> listeners) {
int total = listeners.size();
for (int i = 0; i< total; i++) {
mLocationManager.requestLocationUpdates(
mEnabledProviders.get(i), 0, 0, listeners.get(i));
}
}
/**
* Unregister the listeners with the location providers
*/
protected void unregisterProviders(List<LocationListener> listeners) {
for (LocationListener listener : listeners) {
mLocationManager.removeUpdates(listener);
}
}
/**
* @return the last known location from all providers
*/
protected Location getLastKnownLocation() {
List<String> providers = mLocationManager.getAllProviders();
Location bestLocation = null;
for (String provider : providers) {
Location lastKnownLocation = mLocationManager.getLastKnownLocation(provider);
if (lastKnownLocation != null) {
if (bestLocation == null || bestLocation.getTime() < lastKnownLocation.getTime()) {
bestLocation = lastKnownLocation;
}
}
}
return bestLocation;
}
/**
* @return the timeout for querying the location.
*/
protected long getQueryLocationTimeout() {
return QUERY_LOCATION_TIMEOUT;
}
/**
* @return the total number of enabled location providers
*/
protected int getTotalEnabledProviders() {
if (mEnabledProviders == null) {
mEnabledProviders = mLocationManager.getProviders(true);
}
return mEnabledProviders.size();
}
/**
* Start detecting the country.
* <p>
* Queries the location from all location providers, then starts a thread to query the
* country from GeoCoder.
*/
@Override
public synchronized Country detectCountry() {
if (mLocationListeners != null) {
throw new IllegalStateException();
}
// Request the location from all enabled providers.
int totalProviders = getTotalEnabledProviders();
if (totalProviders > 0) {
mLocationListeners = new ArrayList<LocationListener>(totalProviders);
for (int i = 0; i < totalProviders; i++) {
LocationListener listener = new LocationListener () {
public void onLocationChanged(Location location) {
if (location != null) {
LocationBasedCountryDetector.this.stop();
queryCountryCode(location);
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
mLocationListeners.add(listener);
}
registerEnabledProviders(mLocationListeners);
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
mTimer = null;
LocationBasedCountryDetector.this.stop();
// Looks like no provider could provide the location, let's try the last
// known location.
queryCountryCode(getLastKnownLocation());
}
}, getQueryLocationTimeout());
} else {
// There is no provider enabled.
queryCountryCode(getLastKnownLocation());
}
return mDetectedCountry;
}
/**
* Stop the current query without notifying the listener.
*/
@Override
public synchronized void stop() {
if (mLocationListeners != null) {
unregisterProviders(mLocationListeners);
mLocationListeners = null;
}
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
}
/**
* Start a new thread to query the country from Geocoder.
*/
private synchronized void queryCountryCode(final Location location) {
if (location == null) {
notifyListener(null);
return;
}
if (mQueryThread != null) return;
mQueryThread = new Thread(new Runnable() {
public void run() {
String countryIso = null;
if (location != null) {
countryIso = getCountryFromLocation(location);
}
if (countryIso != null) {
mDetectedCountry = new Country(countryIso, Country.COUNTRY_SOURCE_LOCATION);
} else {
mDetectedCountry = null;
}
notifyListener(mDetectedCountry);
mQueryThread = null;
}
});
mQueryThread.start();
}
}
|