aboutsummaryrefslogtreecommitdiff
path: root/common/src/com/android/tv/common/util/LocationUtils.java
blob: 9d44cf2183d96c66fd3ee9dcb8219246c495035f (plain)
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
/*
 * Copyright (C) 2016 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.tv.common.util;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.android.tv.common.BuildConfig;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

/** A utility class to get the current location. */
public class LocationUtils {
    private static final String TAG = "LocationUtils";
    private static final boolean DEBUG = false;

    private static final Set<OnUpdateAddressListener> sOnUpdateAddressListeners =
            Collections.synchronizedSet(new HashSet<>());

    private static Context sApplicationContext;
    private static Address sAddress;
    private static String sCountry;
    private static IOException sError;

    /** Checks the current location. */
    public static synchronized Address getCurrentAddress(Context context)
            throws IOException, SecurityException {
        if (sAddress != null) {
            return sAddress;
        }
        if (sError != null) {
            throw sError;
        }
        if (sApplicationContext == null) {
            sApplicationContext = context.getApplicationContext();
        }
        /* Begin_AOSP_Comment_Out
        if (!BuildConfig.AOSP) {
            com.google.android.tv.livechannels.util.GoogleLocationUtilsHelper.startLocationUpdates(
                    context, LocationUtils::updateAddress);
            return null;
        }
        End_AOSP_Comment_Out */
        LocationUtilsHelper.startLocationUpdates();
        return null;
    }

    @Nullable
    static String getCurrentPostalCode(Context context) throws IOException {
        Address address = getCurrentAddress(context);
        if (address != null) {
            Log.i(
                    TAG,
                    "Current country and postal code is "
                            + address.getCountryName()
                            + ", "
                            + address.getPostalCode());
            return address.getPostalCode();
        }
        return null;
    }

    /** The listener used when address is updated. */
    public interface OnUpdateAddressListener {
        /**
         * Called when address is updated.
         *
         * <p>This listener is removed when this method returns true.
         *
         * @return {@code true} if the job has been finished and the listener needs to be removed;
         *     {@code false} otherwise.
         */
        boolean onUpdateAddress(Address address);
    }

    /**
     * Add an {@link OnUpdateAddressListener} instance.
     *
     * <p>Note that the listener is removed automatically when {@link
     * OnUpdateAddressListener#onUpdateAddress(Address)} is called and returns {@code true}.
     */
    public static void addOnUpdateAddressListener(OnUpdateAddressListener listener) {
        sOnUpdateAddressListeners.add(listener);
    }

    /**
     * Remove an {@link OnUpdateAddressListener} instance if it exists.
     *
     * <p>Note that the listener will be removed automatically when {@link
     * OnUpdateAddressListener#onUpdateAddress(Address)} is called and returns {@code true}.
     */
    public static void removeOnUpdateAddressListener(OnUpdateAddressListener listener) {
        sOnUpdateAddressListeners.remove(listener);
    }

    /** Returns the current country. */
    @NonNull
    public static synchronized String getCurrentCountry(Context context) {
        if (sCountry != null) {
            return sCountry;
        }
        /* Begin_AOSP_Comment_Out
        if (!BuildConfig.AOSP) {
            sCountry =
                    com.google.android.tv.livechannels.util.GoogleLocationUtilsHelper
                            .getDeviceCountry(context);
        }
        End_AOSP_Comment_Out */
        if (TextUtils.isEmpty(sCountry)) {
            sCountry = context.getResources().getConfiguration().locale.getCountry();
        }
        return sCountry;
    }

    private static void updateAddress(Location location) {
        if (DEBUG) Log.d(TAG, "Updating address with " + location);
        if (location == null) {
            return;
        }
        Geocoder geocoder = new Geocoder(sApplicationContext, Locale.getDefault());
        try {
            List<Address> addresses =
                    geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            if (addresses != null && !addresses.isEmpty()) {
                sAddress = addresses.get(0);
                if (DEBUG) Log.d(TAG, "Got " + sAddress);
                try {
                    PostalCodeUtils.updatePostalCode(sApplicationContext);
                } catch (Exception e) {
                    // Do nothing
                }
                Set<OnUpdateAddressListener> listenersToRemove = new HashSet<>();
                synchronized (sOnUpdateAddressListeners) {
                    for (OnUpdateAddressListener listener : sOnUpdateAddressListeners) {
                        if (listener.onUpdateAddress(sAddress)) {
                            listenersToRemove.add(listener);
                        }
                    }
                    for (OnUpdateAddressListener listener : listenersToRemove) {
                        removeOnUpdateAddressListener(listener);
                    }
                }
            } else {
                if (DEBUG) Log.d(TAG, "No address returned");
            }
            sError = null;
        } catch (IOException e) {
            Log.w(TAG, "Error in updating address", e);
            sError = e;
        }
    }

    private LocationUtils() {}

    private static class LocationUtilsHelper {
        private static final LocationListener LOCATION_LISTENER =
                new LocationListener() {
                    @Override
                    public void onLocationChanged(Location location) {
                        updateAddress(location);
                    }

                    @Override
                    public void onStatusChanged(String provider, int status, Bundle extras) {}

                    @Override
                    public void onProviderEnabled(String provider) {}

                    @Override
                    public void onProviderDisabled(String provider) {}
                };

        private static LocationManager sLocationManager;

        public static void startLocationUpdates() {
            if (sLocationManager == null) {
                sLocationManager =
                        (LocationManager)
                                sApplicationContext.getSystemService(Context.LOCATION_SERVICE);
                try {
                    sLocationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER, 1000, 10, LOCATION_LISTENER, null);
                } catch (SecurityException e) {
                    // Enables requesting the location updates again.
                    sLocationManager = null;
                    throw e;
                }
            }
        }
    }
}