blob: 637bcae7007e013cda7d213cf6a808d928927c5d [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mike Lockwood00b74272010-03-26 10:41:48 -040017package com.android.server.location;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080018
Mike Lockwood29c84342009-05-06 14:01:15 -040019import android.app.AlarmManager;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080020import android.app.AppOpsManager;
Mike Lockwood29c84342009-05-06 14:01:15 -040021import android.app.PendingIntent;
The Android Open Source Project10592532009-03-18 17:39:46 -070022import android.content.BroadcastReceiver;
Yu-Han Yang74041ff2018-04-06 15:57:31 -070023import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.Context;
25import android.content.Intent;
The Android Open Source Project10592532009-03-18 17:39:46 -070026import android.content.IntentFilter;
Soonil Nagarkar35c3b912019-01-31 10:31:24 -080027import android.database.ContentObserver;
destradaa0682809a2013-08-12 18:50:30 -070028import android.hardware.location.GeofenceHardware;
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -070029import android.hardware.location.GeofenceHardwareImpl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.location.Criteria;
destradaa0682809a2013-08-12 18:50:30 -070031import android.location.FusedBatchOptions;
Yu-Han Yange7baef32018-02-09 13:58:17 -080032import android.location.GnssMeasurementsEvent;
33import android.location.GnssNavigationMessage;
Lifu Tang30f95a72016-01-07 23:20:38 -080034import android.location.GnssStatus;
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -070035import android.location.IGpsGeofenceHardware;
Danke Xie22d1f9f2009-08-18 18:28:45 -040036import android.location.INetInitiatedListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.location.Location;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070038import android.location.LocationListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.location.LocationManager;
Stan Chesnutt1d72d8c2013-04-15 19:18:02 -070040import android.location.LocationRequest;
Kevin Tang40e1baf2012-01-10 14:32:44 -080041import android.os.AsyncTask;
Dianne Hackborn91268cf2013-06-13 19:06:50 -070042import android.os.BatteryStats;
Mike Lockwood63aa5a62010-04-14 19:21:31 -040043import android.os.Binder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.Bundle;
Mike Lockwood62a8fc12010-03-22 14:23:26 -040045import android.os.Handler;
Victoria Lease5cd731a2012-12-19 15:04:21 -080046import android.os.Looper;
Mike Lockwood62a8fc12010-03-22 14:23:26 -040047import android.os.Message;
Yu-Han Yange7baef32018-02-09 13:58:17 -080048import android.os.PersistableBundle;
Mike Lockwood0528b9b2009-05-07 10:12:54 -040049import android.os.PowerManager;
Yu-Han Yange7baef32018-02-09 13:58:17 -080050import android.os.PowerManager.ServiceType;
51import android.os.PowerSaveState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.RemoteException;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -040053import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.SystemClock;
Colin Cross7c030ed2014-01-28 09:33:53 -080055import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070056import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070057import android.os.WorkSource;
Narayan Kamath32684dd2018-01-08 17:32:51 +000058import android.os.WorkSource.WorkChain;
Mike Lockwoodbcab8df2009-06-25 16:39:09 -040059import android.provider.Settings;
Yu-Han Yange7baef32018-02-09 13:58:17 -080060import android.telephony.CarrierConfigManager;
Wink Savillea374c3d2014-11-11 11:48:04 -080061import android.telephony.SubscriptionManager;
Miguel Torroja1e84da82010-07-27 07:02:24 +020062import android.telephony.TelephonyManager;
63import android.telephony.gsm.GsmCellLocation;
Colin Cross7c030ed2014-01-28 09:33:53 -080064import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.util.Log;
Yu-Han Yang8a1b51d2018-12-26 22:18:31 -080066import android.util.StatsLog;
WyattRileyba6072f2019-04-18 07:37:52 -070067import android.util.TimeUtils;
Yu-Han Yanga1862b52018-02-20 17:05:59 -080068
Anil Admal032aa812019-03-06 19:23:25 -080069import com.android.internal.annotations.GuardedBy;
Sasha Kuznetsovb9f26b42019-10-03 17:30:46 -070070import com.android.internal.annotations.VisibleForTesting;
jackqdyulei455e90a2017-02-09 15:29:16 -080071import com.android.internal.app.IBatteryStats;
72import com.android.internal.location.GpsNetInitiatedHandler;
73import com.android.internal.location.GpsNetInitiatedHandler.GpsNiNotification;
74import com.android.internal.location.ProviderProperties;
75import com.android.internal.location.ProviderRequest;
Yu-Han Yange7baef32018-02-09 13:58:17 -080076import com.android.internal.location.gnssmetrics.GnssMetrics;
Anil Admale1539e82019-05-09 15:05:04 -070077import com.android.internal.telephony.TelephonyIntents;
Kweku Adams810c77d2019-08-28 07:45:00 -070078import com.android.server.DeviceIdleInternal;
79import com.android.server.LocalServices;
Yu-Han Yang66c7ea92018-03-11 17:17:15 -070080import com.android.server.location.GnssSatelliteBlacklistHelper.GnssSatelliteBlacklistCallback;
Yu-Han Yanga1862b52018-02-20 17:05:59 -080081import com.android.server.location.NtpTimeHelper.InjectNtpTimeCallback;
Yu-Han Yang66c7ea92018-03-11 17:17:15 -070082
Nick Pelly6fa9ad42012-07-16 12:18:23 -070083import java.io.FileDescriptor;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070084import java.io.PrintWriter;
Soonil Nagarkar1575a042018-10-24 17:54:54 -070085import java.lang.annotation.ElementType;
86import java.lang.annotation.Retention;
87import java.lang.annotation.RetentionPolicy;
88import java.lang.annotation.Target;
Wyatt Rileycf879db2017-01-12 13:57:38 -080089import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080090import java.util.Arrays;
Wyatt Rileycf879db2017-01-12 13:57:38 -080091import java.util.List;
Yu-Han Yange7baef32018-02-09 13:58:17 -080092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093/**
gomo4402af62017-01-11 13:20:13 -080094 * A GNSS implementation of LocationProvider used by LocationManager.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 *
96 * {@hide}
97 */
Soonil Nagarkar1575a042018-10-24 17:54:54 -070098public class GnssLocationProvider extends AbstractLocationProvider implements
99 InjectNtpTimeCallback,
100 GnssSatelliteBlacklistCallback {
101
102 /**
103 * Indicates that this method is a native entry point. Useful purely for IDEs which can
104 * understand entry points, and thus eliminate incorrect warnings about methods not used.
105 */
106 @Target(ElementType.METHOD)
107 @Retention(RetentionPolicy.SOURCE)
108 private @interface NativeEntryPoint {
109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Lifu Tang30f95a72016-01-07 23:20:38 -0800111 private static final String TAG = "GnssLocationProvider";
Mike Lockwood29c84342009-05-06 14:01:15 -0400112
Brian Muramatsu1715cb32012-08-08 17:32:21 -0700113 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
114 private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400115
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700116 private static final ProviderProperties PROPERTIES = new ProviderProperties(
117 true, true, false, false, true, true, true,
118 Criteria.POWER_HIGH, Criteria.ACCURACY_FINE);
119
gomo4402af62017-01-11 13:20:13 -0800120 // these need to match GnssPositionMode enum in IGnss.hal
The Android Open Source Project10592532009-03-18 17:39:46 -0700121 private static final int GPS_POSITION_MODE_STANDALONE = 0;
122 private static final int GPS_POSITION_MODE_MS_BASED = 1;
123 private static final int GPS_POSITION_MODE_MS_ASSISTED = 2;
124
gomo4402af62017-01-11 13:20:13 -0800125 // these need to match GnssPositionRecurrence enum in IGnss.hal
Mike Lockwood04598b62010-04-14 17:17:24 -0400126 private static final int GPS_POSITION_RECURRENCE_PERIODIC = 0;
127 private static final int GPS_POSITION_RECURRENCE_SINGLE = 1;
128
gomo4402af62017-01-11 13:20:13 -0800129 // these need to match GnssStatusValue enum in IGnssCallback.hal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 private static final int GPS_STATUS_NONE = 0;
131 private static final int GPS_STATUS_SESSION_BEGIN = 1;
132 private static final int GPS_STATUS_SESSION_END = 2;
133 private static final int GPS_STATUS_ENGINE_ON = 3;
134 private static final int GPS_STATUS_ENGINE_OFF = 4;
135
gomo4402af62017-01-11 13:20:13 -0800136 // these need to match GnssLocationFlags enum in types.hal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 private static final int LOCATION_INVALID = 0;
138 private static final int LOCATION_HAS_LAT_LONG = 1;
139 private static final int LOCATION_HAS_ALTITUDE = 2;
140 private static final int LOCATION_HAS_SPEED = 4;
141 private static final int LOCATION_HAS_BEARING = 8;
gomo4402af62017-01-11 13:20:13 -0800142 private static final int LOCATION_HAS_HORIZONTAL_ACCURACY = 16;
143 private static final int LOCATION_HAS_VERTICAL_ACCURACY = 32;
144 private static final int LOCATION_HAS_SPEED_ACCURACY = 64;
145 private static final int LOCATION_HAS_BEARING_ACCURACY = 128;
Mike Lockwoode3635c92009-05-11 08:38:02 -0400146
Pierre Fite-Georgelb50cdaf2019-02-25 15:42:45 -0800147 // these need to match ElapsedRealtimeFlags enum in types.hal
148 private static final int ELAPSED_REALTIME_HAS_TIMESTAMP_NS = 1;
Pierre Fite-Georgel9e96c572019-02-25 16:12:53 -0800149 private static final int ELAPSED_REALTIME_HAS_TIME_UNCERTAINTY_NS = 2;
Pierre Fite-Georgelb50cdaf2019-02-25 15:42:45 -0800150
gomo4402af62017-01-11 13:20:13 -0800151 // IMPORTANT - the GPS_DELETE_* symbols here must match GnssAidingData enum in IGnss.hal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 private static final int GPS_DELETE_EPHEMERIS = 0x0001;
153 private static final int GPS_DELETE_ALMANAC = 0x0002;
154 private static final int GPS_DELETE_POSITION = 0x0004;
155 private static final int GPS_DELETE_TIME = 0x0008;
156 private static final int GPS_DELETE_IONO = 0x0010;
157 private static final int GPS_DELETE_UTC = 0x0020;
158 private static final int GPS_DELETE_HEALTH = 0x0040;
159 private static final int GPS_DELETE_SVDIR = 0x0080;
160 private static final int GPS_DELETE_SVSTEER = 0x0100;
161 private static final int GPS_DELETE_SADATA = 0x0200;
162 private static final int GPS_DELETE_RTI = 0x0400;
163 private static final int GPS_DELETE_CELLDB_INFO = 0x8000;
164 private static final int GPS_DELETE_ALL = 0xFFFF;
165
gomo4402af62017-01-11 13:20:13 -0800166 // The GPS_CAPABILITY_* flags must match Capabilities enum in IGnssCallback.hal
Mike Lockwood04598b62010-04-14 17:17:24 -0400167 private static final int GPS_CAPABILITY_SCHEDULING = 0x0000001;
168 private static final int GPS_CAPABILITY_MSB = 0x0000002;
169 private static final int GPS_CAPABILITY_MSA = 0x0000004;
170 private static final int GPS_CAPABILITY_SINGLE_SHOT = 0x0000008;
Mike Lockwood9b9fb5c2011-06-29 15:09:40 -0400171 private static final int GPS_CAPABILITY_ON_DEMAND_TIME = 0x0000010;
Anil Admalefd9dc62019-03-12 17:39:20 -0700172 public static final int GPS_CAPABILITY_GEOFENCING = 0x0000020;
gomo226b7b72018-12-12 16:49:39 -0800173 public static final int GPS_CAPABILITY_MEASUREMENTS = 0x0000040;
Anil Admalefd9dc62019-03-12 17:39:20 -0700174 public static final int GPS_CAPABILITY_NAV_MESSAGES = 0x0000080;
Anil Admal62c42dc2019-04-03 15:39:22 -0700175 public static final int GPS_CAPABILITY_LOW_POWER_MODE = 0x0000100;
176 public static final int GPS_CAPABILITY_SATELLITE_BLACKLIST = 0x0000200;
177 public static final int GPS_CAPABILITY_MEASUREMENT_CORRECTIONS = 0x0000400;
Mike Lockwood04598b62010-04-14 17:17:24 -0400178
Tsuwei Chen462bcd82014-09-17 12:28:49 -0700179 // The AGPS SUPL mode
180 private static final int AGPS_SUPL_MODE_MSA = 0x02;
181 private static final int AGPS_SUPL_MODE_MSB = 0x01;
182
Kweku Adams810c77d2019-08-28 07:45:00 -0700183 private static final int UPDATE_LOW_POWER_MODE = 1;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700184 private static final int SET_REQUEST = 3;
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400185 private static final int INJECT_NTP_TIME = 5;
Kevin Tang8c6ac672019-03-22 12:31:01 -0700186 // PSDS stands for Predicted Satellite Data Service
187 private static final int DOWNLOAD_PSDS_DATA = 6;
Kevin Tang8c6ac672019-03-22 12:31:01 -0700188 private static final int DOWNLOAD_PSDS_DATA_FINISHED = 11;
destradaafb23c672015-04-16 14:01:27 -0700189 private static final int INITIALIZE_HANDLER = 13;
Yu-Han Yange7baef32018-02-09 13:58:17 -0800190 private static final int REQUEST_LOCATION = 16;
Wyatt Riley26465d22018-02-12 13:44:24 -0800191 private static final int REPORT_LOCATION = 17; // HAL reports location
192 private static final int REPORT_SV_STATUS = 18; // HAL reports SV status
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400193
Miguel Torroja1e84da82010-07-27 07:02:24 +0200194 // Request setid
195 private static final int AGPS_RIL_REQUEST_SETID_IMSI = 1;
196 private static final int AGPS_RIL_REQUEST_SETID_MSISDN = 2;
197
Miguel Torroja1e84da82010-07-27 07:02:24 +0200198 // ref. location info
199 private static final int AGPS_REF_LOCATION_TYPE_GSM_CELLID = 1;
200 private static final int AGPS_REF_LOCATION_TYPE_UMTS_CELLID = 2;
Miguel Torroja1e84da82010-07-27 07:02:24 +0200201
202 // set id info
203 private static final int AGPS_SETID_TYPE_NONE = 0;
204 private static final int AGPS_SETID_TYPE_IMSI = 1;
205 private static final int AGPS_SETID_TYPE_MSISDN = 2;
206
gomo48f1a642017-11-10 20:35:46 -0800207 private static final int GPS_GEOFENCE_UNAVAILABLE = 1 << 0L;
208 private static final int GPS_GEOFENCE_AVAILABLE = 1 << 1L;
destradaa0682809a2013-08-12 18:50:30 -0700209
gomo4402af62017-01-11 13:20:13 -0800210 // GPS Geofence errors. Should match GeofenceStatus enum in IGnssGeofenceCallback.hal.
destradaa0682809a2013-08-12 18:50:30 -0700211 private static final int GPS_GEOFENCE_OPERATION_SUCCESS = 0;
212 private static final int GPS_GEOFENCE_ERROR_TOO_MANY_GEOFENCES = 100;
gomo48f1a642017-11-10 20:35:46 -0800213 private static final int GPS_GEOFENCE_ERROR_ID_EXISTS = -101;
destradaa0682809a2013-08-12 18:50:30 -0700214 private static final int GPS_GEOFENCE_ERROR_ID_UNKNOWN = -102;
215 private static final int GPS_GEOFENCE_ERROR_INVALID_TRANSITION = -103;
216 private static final int GPS_GEOFENCE_ERROR_GENERIC = -149;
217
Tsuwei Chen678c13c2014-09-22 17:48:41 -0700218 // TCP/IP constants.
219 // Valid TCP/UDP port range is (0, 65535].
220 private static final int TCP_MIN_PORT = 0;
221 private static final int TCP_MAX_PORT = 0xffff;
222
Yu-Han Yange7baef32018-02-09 13:58:17 -0800223 // 1 second, or 1 Hz frequency.
224 private static final long LOCATION_UPDATE_MIN_TIME_INTERVAL_MILLIS = 1000;
Yu-Han Yang639f7592018-06-07 11:58:52 -0700225 // Default update duration in milliseconds for REQUEST_LOCATION.
Yu-Han Yang9e2a8232018-06-14 12:10:08 -0700226 private static final long LOCATION_UPDATE_DURATION_MILLIS = 10 * 1000;
Anil Admalb1c6c0d2019-06-20 12:00:16 -0700227 // Update duration extension multiplier for emergency REQUEST_LOCATION.
228 private static final int EMERGENCY_LOCATION_UPDATE_DURATION_MULTIPLIER = 3;
Yu-Han Yange7baef32018-02-09 13:58:17 -0800229
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700230 /** simpler wrapper for ProviderRequest + Worksource */
231 private static class GpsRequest {
232 public ProviderRequest request;
233 public WorkSource source;
gomo48f1a642017-11-10 20:35:46 -0800234
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700235 public GpsRequest(ProviderRequest request, WorkSource source) {
236 this.request = request;
237 this.source = source;
238 }
239 }
240
Wyatt Riley26465d22018-02-12 13:44:24 -0800241 // Threadsafe class to hold stats reported in the Extras Bundle
Wyatt Rileyc7067412018-02-07 15:50:35 -0800242 private static class LocationExtras {
243 private int mSvCount;
244 private int mMeanCn0;
245 private int mMaxCn0;
246 private final Bundle mBundle;
247
248 public LocationExtras() {
249 mBundle = new Bundle();
250 }
251
252 public void set(int svCount, int meanCn0, int maxCn0) {
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700253 synchronized (this) {
Wyatt Riley26465d22018-02-12 13:44:24 -0800254 mSvCount = svCount;
255 mMeanCn0 = meanCn0;
256 mMaxCn0 = maxCn0;
257 }
Wyatt Rileyc7067412018-02-07 15:50:35 -0800258 setBundle(mBundle);
259 }
260
261 public void reset() {
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700262 set(0, 0, 0);
Wyatt Rileyc7067412018-02-07 15:50:35 -0800263 }
264
265 // Also used by outside methods to add to other bundles
266 public void setBundle(Bundle extras) {
267 if (extras != null) {
Wyatt Riley26465d22018-02-12 13:44:24 -0800268 synchronized (this) {
269 extras.putInt("satellites", mSvCount);
270 extras.putInt("meanCn0", mMeanCn0);
271 extras.putInt("maxCn0", mMaxCn0);
272 }
Wyatt Rileyc7067412018-02-07 15:50:35 -0800273 }
274 }
275
276 public Bundle getBundle() {
Wyatt Riley26465d22018-02-12 13:44:24 -0800277 synchronized (this) {
278 return new Bundle(mBundle);
279 }
Wyatt Rileyc7067412018-02-07 15:50:35 -0800280 }
281 }
282
Yu-Han Yang66c7ea92018-03-11 17:17:15 -0700283 private final Object mLock = new Object();
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700284
Mike Lockwood0632ca72009-05-14 15:51:03 -0400285 // stop trying if we do not receive a fix within 60 seconds
Mike Lockwood04598b62010-04-14 17:17:24 -0400286 private static final int NO_FIX_TIMEOUT = 60 * 1000;
Mike Lockwood0632ca72009-05-14 15:51:03 -0400287
Nick Pellyb041f232012-05-07 17:12:25 -0700288 // if the fix interval is below this we leave GPS on,
289 // if above then we cycle the GPS driver.
290 // Typical hot TTTF is ~5 seconds, so 10 seconds seems sane.
291 private static final int GPS_POLLING_THRESHOLD_INTERVAL = 10 * 1000;
292
Kevin Tang8c6ac672019-03-22 12:31:01 -0700293 // how long to wait if we have a network error in NTP or PSDS downloading
Wei Liu6f6326b2015-06-24 23:47:50 -0700294 // the initial value of the exponential backoff
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700295 // current setting - 5 minutes
gomo48f1a642017-11-10 20:35:46 -0800296 private static final long RETRY_INTERVAL = 5 * 60 * 1000;
Kevin Tang8c6ac672019-03-22 12:31:01 -0700297 // how long to wait if we have a network error in NTP or PSDS downloading
Wei Liu6f6326b2015-06-24 23:47:50 -0700298 // the max value of the exponential backoff
299 // current setting - 4 hours
gomo48f1a642017-11-10 20:35:46 -0800300 private static final long MAX_RETRY_INTERVAL = 4 * 60 * 60 * 1000;
Wei Liu6f6326b2015-06-24 23:47:50 -0700301
Kevin Tang8c6ac672019-03-22 12:31:01 -0700302 // Timeout when holding wakelocks for downloading PSDS data.
303 private static final long DOWNLOAD_PSDS_DATA_TIMEOUT_MS = 60 * 1000;
Yu-Han Yang499a6ba2019-11-14 14:19:13 -0800304 private static final long WAKELOCK_TIMEOUT_MILLIS = 30 * 1000;
Wei Wangc5706f62017-04-18 11:26:26 -0700305
Kevin Tang8c6ac672019-03-22 12:31:01 -0700306 private final ExponentialBackOff mPsdsBackOff = new ExponentialBackOff(RETRY_INTERVAL,
Yu-Han Yanga1862b52018-02-20 17:05:59 -0800307 MAX_RETRY_INTERVAL);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700308
Sasha Kuznetsovb9f26b42019-10-03 17:30:46 -0700309 private static boolean sIsInitialized = false;
310 private static boolean sStaticTestOverride = false;
311
Yu-Han Yang76f99952019-05-04 17:45:44 -0700312 // True if we are enabled
313 @GuardedBy("mLock")
314 private boolean mGpsEnabled;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700315
Soonil Nagarkar35c3b912019-01-31 10:31:24 -0800316 private boolean mShutdown;
317
Kevin Tang8c6ac672019-03-22 12:31:01 -0700318 // states for injecting ntp and downloading psds data
Kevin Tang40e1baf2012-01-10 14:32:44 -0800319 private static final int STATE_PENDING_NETWORK = 0;
320 private static final int STATE_DOWNLOADING = 1;
321 private static final int STATE_IDLE = 2;
322
Kevin Tang8c6ac672019-03-22 12:31:01 -0700323 // flags to trigger NTP or PSDS data download when network becomes available
324 // initialized to true so we do NTP and PSDS when the network comes up after booting
325 private int mDownloadPsdsDataPending = STATE_PENDING_NETWORK;
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 // true if GPS is navigating
328 private boolean mNavigating;
Mike Lockwoodcf1d8cb2010-01-20 10:14:54 -0500329
Mike Lockwood04598b62010-04-14 17:17:24 -0400330 // requested frequency of fixes, in milliseconds
331 private int mFixInterval = 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332
gomo48f1a642017-11-10 20:35:46 -0800333 // true if low power mode for the GNSS chipset is part of the latest request.
334 private boolean mLowPowerMode = false;
335
WyattRileyba6072f2019-04-18 07:37:52 -0700336 // true if we started navigation in the HAL, only change value of this in setStarted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 private boolean mStarted;
338
WyattRileyba6072f2019-04-18 07:37:52 -0700339 // for logging of latest change, and warning of ongoing location after a stop
340 private long mStartedChangedElapsedRealtime;
341
342 // threshold for delay in GNSS engine turning off before warning & error
343 private static final long LOCATION_OFF_DELAY_THRESHOLD_WARN_MILLIS = 2 * 1000;
344 private static final long LOCATION_OFF_DELAY_THRESHOLD_ERROR_MILLIS = 15 * 1000;
345
Anil Admal312fddb2019-03-25 12:15:43 -0700346 // capabilities reported through the top level IGnssCallback.hal
347 private volatile int mTopHalCapabilities;
Mike Lockwood04598b62010-04-14 17:17:24 -0400348
Kevin Tang8c6ac672019-03-22 12:31:01 -0700349 // true if PSDS is supported
350 private boolean mSupportsPsds;
Mike Lockwood1a1cd3a2010-08-17 07:42:54 -0400351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800352 // for calculating time to first fix
353 private long mFixRequestTime = 0;
354 // time to first fix for most recent session
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700355 private int mTimeToFirstFix = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 // time we received our last fix
357 private long mLastFixTime;
358
Mike Lockwood04598b62010-04-14 17:17:24 -0400359 private int mPositionMode;
Yu-Han Yangc8b9ff72018-04-17 00:47:24 -0700360 private GnssPositionMode mLastPositionMode;
Mike Lockwood04598b62010-04-14 17:17:24 -0400361
David Christied4edf4c2014-08-12 15:22:27 -0700362 // Current request from underlying location clients.
Soonil Nagarkar35c3b912019-01-31 10:31:24 -0800363 private ProviderRequest mProviderRequest;
Narayan Kamath32684dd2018-01-08 17:32:51 +0000364 // The WorkSource associated with the most recent client request (i.e, most recent call to
365 // setRequest).
David Christied4edf4c2014-08-12 15:22:27 -0700366 private WorkSource mWorkSource = null;
WyattRileyb2446072019-03-01 07:41:49 -0800367 // True if gps should be disabled because of PowerManager controls
368 private boolean mDisableGpsForPowerManager = false;
David Christied4edf4c2014-08-12 15:22:27 -0700369
destradaafb23c672015-04-16 14:01:27 -0700370 /**
Kweku Adams810c77d2019-08-28 07:45:00 -0700371 * True if the device idle controller has determined that the device is stationary. This is only
372 * updated when the device enters idle mode.
373 */
374 private volatile boolean mIsDeviceStationary = false;
375
376 /**
destradaafb23c672015-04-16 14:01:27 -0700377 * Properties loaded from PROPERTIES_FILE.
378 * It must be accessed only inside {@link #mHandler}.
379 */
Anil Admald71cf142018-12-21 14:59:36 -0800380 private GnssConfiguration mGnssConfiguration;
destradaafb23c672015-04-16 14:01:27 -0700381
Mike Lockwood734d6032009-07-28 18:30:25 -0700382 private String mSuplServerHost;
Tsuwei Chen678c13c2014-09-22 17:48:41 -0700383 private int mSuplServerPort = TCP_MIN_PORT;
Mike Lockwood734d6032009-07-28 18:30:25 -0700384 private String mC2KServerHost;
385 private int mC2KServerPort;
Tsuwei Chen3324e952014-09-07 01:30:42 -0700386 private boolean mSuplEsEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387
Anil Admal94ec76a2019-01-15 09:42:01 -0800388 private final Looper mLooper;
Wyatt Rileyc7067412018-02-07 15:50:35 -0800389 private final LocationExtras mLocationExtras = new LocationExtras();
Anil Admal75b9fd62018-11-28 11:22:50 -0800390 private final GnssStatusListenerHelper mGnssStatusListenerHelper;
Lifu Tang818aa2c2016-02-01 01:52:00 -0800391 private final GnssMeasurementsProvider mGnssMeasurementsProvider;
Anil Admalefd9dc62019-03-12 17:39:20 -0700392 private final GnssMeasurementCorrectionsProvider mGnssMeasurementCorrectionsProvider;
Lifu Tang818aa2c2016-02-01 01:52:00 -0800393 private final GnssNavigationMessageProvider mGnssNavigationMessageProvider;
Yu-Han Yang07561382018-02-21 13:08:37 -0800394 private final LocationChangeListener mNetworkLocationListener = new NetworkLocationListener();
395 private final LocationChangeListener mFusedLocationListener = new FusedLocationListener();
Yu-Han Yanga1862b52018-02-20 17:05:59 -0800396 private final NtpTimeHelper mNtpTimeHelper;
Yu-Han Yang3557cc72018-03-21 12:48:36 -0700397 private final GnssBatchingProvider mGnssBatchingProvider;
Yu-Han Yang890ca8b2018-04-16 22:11:31 -0700398 private final GnssGeofenceProvider mGnssGeofenceProvider;
Anil Admal312fddb2019-03-25 12:15:43 -0700399 private final GnssCapabilitiesProvider mGnssCapabilitiesProvider;
400
Anil Admal316f9482019-02-12 18:57:18 -0800401 // Available only on GNSS HAL 2.0 implementations and later.
Anil Admal94ec76a2019-01-15 09:42:01 -0800402 private GnssVisibilityControl mGnssVisibilityControl;
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400403
Victoria Lease5c24fd02012-10-01 11:00:50 -0700404 // Handler for processing events
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400405 private Handler mHandler;
The Android Open Source Project10592532009-03-18 17:39:46 -0700406
Anil Admal50ba15e2018-11-01 16:42:42 -0700407 private final GnssNetworkConnectivityHandler mNetworkConnectivityHandler;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700408 private final GpsNetInitiatedHandler mNIHandler;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400409
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400410 // Wakelocks
Lifu Tang30f95a72016-01-07 23:20:38 -0800411 private final static String WAKELOCK_KEY = "GnssLocationProvider";
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400412 private final PowerManager.WakeLock mWakeLock;
Kevin Tang8c6ac672019-03-22 12:31:01 -0700413 private static final String DOWNLOAD_EXTRA_WAKELOCK_KEY = "GnssLocationProviderPsdsDownload";
Yu-Han Yang76f99952019-05-04 17:45:44 -0700414 @GuardedBy("mLock")
Kevin Tang8c6ac672019-03-22 12:31:01 -0700415 private final PowerManager.WakeLock mDownloadPsdsWakeLock;
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400416
Mike Lockwood29c84342009-05-06 14:01:15 -0400417 // Alarms
418 private final static String ALARM_WAKEUP = "com.android.internal.location.ALARM_WAKEUP";
Mike Lockwood0632ca72009-05-14 15:51:03 -0400419 private final static String ALARM_TIMEOUT = "com.android.internal.location.ALARM_TIMEOUT";
Tsuwei Chen52617bb2014-08-25 11:49:11 -0700420
David Christied4edf4c2014-08-12 15:22:27 -0700421 private final PowerManager mPowerManager;
Mike Lockwood29c84342009-05-06 14:01:15 -0400422 private final AlarmManager mAlarmManager;
423 private final PendingIntent mWakeupIntent;
Mike Lockwood0632ca72009-05-14 15:51:03 -0400424 private final PendingIntent mTimeoutIntent;
Mike Lockwood29c84342009-05-06 14:01:15 -0400425
Svet Ganovf7b47252018-02-26 11:11:27 -0800426 private final AppOpsManager mAppOps;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400427 private final IBatteryStats mBatteryStats;
The Android Open Source Project10592532009-03-18 17:39:46 -0700428
Narayan Kamath32684dd2018-01-08 17:32:51 +0000429 // Current list of underlying location clients.
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700430 // only modified on handler thread
Dianne Hackborn002a54e2013-01-10 17:34:55 -0800431 private WorkSource mClientSource = new WorkSource();
Mike Lockwoodf1218be2010-01-29 09:20:06 -0500432
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700433 private GeofenceHardwareImpl mGeofenceHardwareImpl;
Wyatt Rileyd87cf912017-12-05 09:31:52 -0800434
435 // Volatile for simple inter-thread sync on these values.
436 private volatile int mHardwareYear = 0;
Wyatt Riley49097c02018-03-15 09:14:43 -0700437 private volatile String mHardwareModelName;
Lifu Tang82f893d2016-01-21 18:15:33 -0800438
Wyatt Riley5d5bac82016-11-01 07:05:16 -0700439 // Set lower than the current ITAR limit of 600m/s to allow this to trigger even if GPS HAL
440 // stops output right at 600m/s, depriving this of the information of a device that reaches
441 // greater than 600m/s, and higher than the speed of sound to avoid impacting most use cases.
442 private static final float ITAR_SPEED_LIMIT_METERS_PER_SECOND = 400.0F;
Wyatt Riley042c48f2017-10-06 14:59:25 -0700443
Wyatt Riley042c48f2017-10-06 14:59:25 -0700444 private volatile boolean mItarSpeedLimitExceeded = false;
Wyatt Riley5d5bac82016-11-01 07:05:16 -0700445
Siddharth Raybb608c82017-03-16 11:33:34 -0700446 // GNSS Metrics
447 private GnssMetrics mGnssMetrics;
448
Anil Admal75b9fd62018-11-28 11:22:50 -0800449 public GnssStatusListenerHelper getGnssStatusProvider() {
450 return mGnssStatusListenerHelper;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400451 }
452
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700453 public IGpsGeofenceHardware getGpsGeofenceProxy() {
Yu-Han Yang890ca8b2018-04-16 22:11:31 -0700454 return mGnssGeofenceProvider;
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700455 }
456
Lifu Tang818aa2c2016-02-01 01:52:00 -0800457 public GnssMeasurementsProvider getGnssMeasurementsProvider() {
458 return mGnssMeasurementsProvider;
destradaaea8a8a62014-06-23 18:19:03 -0700459 }
460
Anil Admalefd9dc62019-03-12 17:39:20 -0700461 public GnssMeasurementCorrectionsProvider getGnssMeasurementCorrectionsProvider() {
462 return mGnssMeasurementCorrectionsProvider;
463 }
464
Lifu Tang818aa2c2016-02-01 01:52:00 -0800465 public GnssNavigationMessageProvider getGnssNavigationMessageProvider() {
466 return mGnssNavigationMessageProvider;
destradaa4b3e3932014-07-21 18:01:47 -0700467 }
Kweku Adams810c77d2019-08-28 07:45:00 -0700468
469 private final DeviceIdleInternal.StationaryListener mDeviceIdleStationaryListener =
470 isStationary -> {
471 mIsDeviceStationary = isStationary;
472 // Call updateLowPowerMode on handler thread so it's always called from the same
473 // thread.
474 mHandler.sendEmptyMessage(UPDATE_LOW_POWER_MODE);
475 };
476
Tsuwei Chen52617bb2014-08-25 11:49:11 -0700477 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
gomo48f1a642017-11-10 20:35:46 -0800478 @Override
479 public void onReceive(Context context, Intent intent) {
The Android Open Source Project10592532009-03-18 17:39:46 -0700480 String action = intent.getAction();
Tsuwei Chen48d37f92014-09-05 15:15:34 -0700481 if (DEBUG) Log.d(TAG, "receive broadcast intent, action: " + action);
destradaaee9fd342015-08-31 13:31:17 -0700482 if (action == null) {
483 return;
484 }
485
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700486 switch (action) {
487 case ALARM_WAKEUP:
Yu-Han Yang6a5f0b72019-01-24 18:34:28 -0800488 startNavigating();
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700489 break;
490 case ALARM_TIMEOUT:
491 hibernate();
492 break;
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700493 case PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED:
Kweku Adams810c77d2019-08-28 07:45:00 -0700494 DeviceIdleInternal deviceIdleService = LocalServices.getService(
495 DeviceIdleInternal.class);
496 if (mPowerManager.isDeviceIdleMode()) {
497 deviceIdleService.registerStationaryListener(mDeviceIdleStationaryListener);
498 } else {
499 deviceIdleService.unregisterStationaryListener(
500 mDeviceIdleStationaryListener);
501 }
502 // Intentional fall-through.
503 case PowerManager.ACTION_POWER_SAVE_MODE_CHANGED:
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700504 case Intent.ACTION_SCREEN_OFF:
505 case Intent.ACTION_SCREEN_ON:
Kweku Adams810c77d2019-08-28 07:45:00 -0700506 // Call updateLowPowerMode on handler thread so it's always called from the
507 // same thread.
508 mHandler.sendEmptyMessage(UPDATE_LOW_POWER_MODE);
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700509 break;
Meng Wang19b214d2018-11-07 12:14:39 -0800510 case CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED:
Anil Admale1539e82019-05-09 15:05:04 -0700511 case TelephonyIntents.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED:
Soonil Nagarkarfc9c7f82019-07-16 12:07:57 -0700512 subscriptionOrCarrierConfigChanged();
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700513 break;
David Christied4edf4c2014-08-12 15:22:27 -0700514 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700515 }
Mike Lockwood29c84342009-05-06 14:01:15 -0400516 };
The Android Open Source Project10592532009-03-18 17:39:46 -0700517
Yu-Han Yang66c7ea92018-03-11 17:17:15 -0700518 /**
519 * Implements {@link GnssSatelliteBlacklistCallback#onUpdateSatelliteBlacklist}.
520 */
521 @Override
522 public void onUpdateSatelliteBlacklist(int[] constellations, int[] svids) {
Anil Admald71cf142018-12-21 14:59:36 -0800523 mHandler.post(() -> mGnssConfiguration.setSatelliteBlacklist(constellations, svids));
Yu-Han Yang284234e2019-03-28 19:35:57 -0700524 mGnssMetrics.resetConstellationTypes();
Yu-Han Yang66c7ea92018-03-11 17:17:15 -0700525 }
526
Soonil Nagarkarfc9c7f82019-07-16 12:07:57 -0700527 private void subscriptionOrCarrierConfigChanged() {
Joe Onorato0c484102016-02-01 18:04:24 -0800528 if (DEBUG) Log.d(TAG, "received SIM related action: ");
Wink Savillea374c3d2014-11-11 11:48:04 -0800529 TelephonyManager phone = (TelephonyManager)
530 mContext.getSystemService(Context.TELEPHONY_SERVICE);
Ecco Park4fa1ab72016-10-24 13:04:52 -0700531 CarrierConfigManager configManager = (CarrierConfigManager)
532 mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
Anil Admale1539e82019-05-09 15:05:04 -0700533 int ddSubId = SubscriptionManager.getDefaultDataSubscriptionId();
534 String mccMnc = SubscriptionManager.isValidSubscriptionId(ddSubId)
535 ? phone.getSimOperator(ddSubId) : phone.getSimOperator();
Ecco Park4fa1ab72016-10-24 13:04:52 -0700536 boolean isKeepLppProfile = false;
Wink Savillea374c3d2014-11-11 11:48:04 -0800537 if (!TextUtils.isEmpty(mccMnc)) {
Joe Onorato0c484102016-02-01 18:04:24 -0800538 if (DEBUG) Log.d(TAG, "SIM MCC/MNC is available: " + mccMnc);
Yu-Han Yang76f99952019-05-04 17:45:44 -0700539 if (configManager != null) {
Anil Admale1539e82019-05-09 15:05:04 -0700540 PersistableBundle b = SubscriptionManager.isValidSubscriptionId(ddSubId)
541 ? configManager.getConfigForSubId(ddSubId) : null;
Yu-Han Yang76f99952019-05-04 17:45:44 -0700542 if (b != null) {
543 isKeepLppProfile =
544 b.getBoolean(CarrierConfigManager.Gps.KEY_PERSIST_LPP_MODE_BOOL);
Ecco Park4fa1ab72016-10-24 13:04:52 -0700545 }
Wink Savillea374c3d2014-11-11 11:48:04 -0800546 }
Yu-Han Yang76f99952019-05-04 17:45:44 -0700547 if (isKeepLppProfile) {
548 // load current properties for the carrier
549 mGnssConfiguration.loadPropertiesFromCarrierConfig();
550 String lpp_profile = mGnssConfiguration.getLppProfile();
551 // set the persist property LPP_PROFILE for the value
552 if (lpp_profile != null) {
553 SystemProperties.set(GnssConfiguration.LPP_PROFILE, lpp_profile);
554 }
555 } else {
556 // reset the persist property
557 SystemProperties.set(GnssConfiguration.LPP_PROFILE, "");
558 }
559 reloadGpsProperties();
Wink Savillea374c3d2014-11-11 11:48:04 -0800560 } else {
Joe Onorato0c484102016-02-01 18:04:24 -0800561 if (DEBUG) Log.d(TAG, "SIM MCC/MNC is still not available");
Wink Savillea374c3d2014-11-11 11:48:04 -0800562 }
563 }
564
David Christied4edf4c2014-08-12 15:22:27 -0700565 private void updateLowPowerMode() {
Kweku Adams810c77d2019-08-28 07:45:00 -0700566 // Disable GPS if we are in device idle mode and the device is stationary.
567 boolean disableGpsForPowerManager = mPowerManager.isDeviceIdleMode() && mIsDeviceStationary;
568 final PowerSaveState result = mPowerManager.getPowerSaveState(ServiceType.LOCATION);
Kweku Adams731a1032019-02-04 14:05:41 -0800569 switch (result.locationMode) {
Makoto Onuki57f0f552017-12-11 12:22:18 -0800570 case PowerManager.LOCATION_MODE_GPS_DISABLED_WHEN_SCREEN_OFF:
Kweku Adams5e0052b2019-02-22 15:17:52 -0800571 case PowerManager.LOCATION_MODE_ALL_DISABLED_WHEN_SCREEN_OFF:
Adam Lesinski87c17df2015-05-27 13:24:13 -0700572 // If we are in battery saver mode and the screen is off, disable GPS.
WyattRileyb2446072019-03-01 07:41:49 -0800573 disableGpsForPowerManager |=
574 result.batterySaverEnabled && !mPowerManager.isInteractive();
David Christied4edf4c2014-08-12 15:22:27 -0700575 break;
David Christied4edf4c2014-08-12 15:22:27 -0700576 }
WyattRileyb2446072019-03-01 07:41:49 -0800577 if (disableGpsForPowerManager != mDisableGpsForPowerManager) {
578 mDisableGpsForPowerManager = disableGpsForPowerManager;
Soonil Nagarkar35c3b912019-01-31 10:31:24 -0800579 updateEnabled();
David Christied4edf4c2014-08-12 15:22:27 -0700580 updateRequirements();
581 }
582 }
583
Sasha Kuznetsovb9f26b42019-10-03 17:30:46 -0700584 @VisibleForTesting
585 public static void setIsSupportedForTest(boolean override) {
586 sStaticTestOverride = override;
587 }
588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 public static boolean isSupported() {
Sasha Kuznetsovb9f26b42019-10-03 17:30:46 -0700590 if (sStaticTestOverride) {
591 return true;
592 }
Sasha Kuznetsov24da7f92019-11-01 12:21:50 -0700593 ensureInitialized();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 return native_is_supported();
595 }
596
Sasha Kuznetsov24da7f92019-11-01 12:21:50 -0700597 private static synchronized void ensureInitialized() {
598 if (!sIsInitialized) {
599 class_init_native();
600 }
601 sIsInitialized = true;
602 }
603
Anil Admald71cf142018-12-21 14:59:36 -0800604 private void reloadGpsProperties() {
605 mGnssConfiguration.reloadGpsProperties();
606 setSuplHostPort();
Tsuwei Chen52617bb2014-08-25 11:49:11 -0700607 // TODO: we should get rid of C2K specific setting.
Anil Admald71cf142018-12-21 14:59:36 -0800608 mC2KServerHost = mGnssConfiguration.getC2KHost();
609 mC2KServerPort = mGnssConfiguration.getC2KPort(TCP_MIN_PORT);
610 mNIHandler.setEmergencyExtensionSeconds(mGnssConfiguration.getEsExtensionSec());
611 mSuplEsEnabled = mGnssConfiguration.getSuplEs(0) == 1;
Anil Admale1539e82019-05-09 15:05:04 -0700612 mNIHandler.setSuplEsEnabled(mSuplEsEnabled);
Anil Admal94ec76a2019-01-15 09:42:01 -0800613 if (mGnssVisibilityControl != null) {
Anil Admale1539e82019-05-09 15:05:04 -0700614 mGnssVisibilityControl.onConfigurationUpdated(mGnssConfiguration);
Anil Admal94ec76a2019-01-15 09:42:01 -0800615 }
Colin Cross7c030ed2014-01-28 09:33:53 -0800616 }
617
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700618 public GnssLocationProvider(Context context, LocationProviderManager locationProviderManager,
Victoria Lease5cd731a2012-12-19 15:04:21 -0800619 Looper looper) {
Soonil Nagarkar0d77ea62019-01-31 14:36:56 -0800620 super(context, locationProviderManager);
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700621
Sasha Kuznetsov24da7f92019-11-01 12:21:50 -0700622 ensureInitialized();
Sasha Kuznetsovb9f26b42019-10-03 17:30:46 -0700623
Anil Admal94ec76a2019-01-15 09:42:01 -0800624 mLooper = looper;
Mike Lockwood63598a02010-02-24 11:52:59 -0500625
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400626 // Create a wake lock
David Christied4edf4c2014-08-12 15:22:27 -0700627 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
628 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700629 mWakeLock.setReferenceCounted(true);
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400630
Kevin Tang8c6ac672019-03-22 12:31:01 -0700631 // Create a separate wake lock for psds downloader as it may be released due to timeout.
632 mDownloadPsdsWakeLock = mPowerManager.newWakeLock(
Wei Wangb71c0492017-05-01 20:24:19 -0700633 PowerManager.PARTIAL_WAKE_LOCK, DOWNLOAD_EXTRA_WAKELOCK_KEY);
Kevin Tang8c6ac672019-03-22 12:31:01 -0700634 mDownloadPsdsWakeLock.setReferenceCounted(true);
Wei Wangb71c0492017-05-01 20:24:19 -0700635
gomo48f1a642017-11-10 20:35:46 -0800636 mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
Mike Lockwood29c84342009-05-06 14:01:15 -0400637 mWakeupIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ALARM_WAKEUP), 0);
Mike Lockwood0632ca72009-05-14 15:51:03 -0400638 mTimeoutIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ALARM_TIMEOUT), 0);
Mike Lockwood29c84342009-05-06 14:01:15 -0400639
Anil Admal312fddb2019-03-25 12:15:43 -0700640 mNetworkConnectivityHandler = new GnssNetworkConnectivityHandler(context,
641 GnssLocationProvider.this::onNetworkAvailable, looper);
Mike Lockwood58bda982009-04-14 16:25:07 -0400642
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800643 // App ops service to keep track of who is accessing the GPS
Svet Ganovf7b47252018-02-26 11:11:27 -0800644 mAppOps = mContext.getSystemService(AppOpsManager.class);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800645
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400646 // Battery statistics service to be notified when GPS turns on or off
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700647 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
648 BatteryStats.SERVICE_NAME));
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400649
destradaafb23c672015-04-16 14:01:27 -0700650 // Construct internal handler
651 mHandler = new ProviderHandler(looper);
652
653 // Load GPS configuration and register listeners in the background:
654 // some operations, such as opening files and registering broadcast receivers, can take a
655 // relative long time, so the ctor() is kept to create objects needed by this instance,
656 // while IO initialization and registration is delegated to our internal handler
657 // this approach is just fine because events are posted to our handler anyway
Anil Admald71cf142018-12-21 14:59:36 -0800658 mGnssConfiguration = new GnssConfiguration(mContext);
Anil Admal312fddb2019-03-25 12:15:43 -0700659 mGnssCapabilitiesProvider = new GnssCapabilitiesProvider();
WyattRileyd1309312019-02-28 12:11:45 -0800660 // Create a GPS net-initiated handler (also needed by handleInitialize)
Tsuwei Chen3324e952014-09-07 01:30:42 -0700661 mNIHandler = new GpsNetInitiatedHandler(context,
gomo48f1a642017-11-10 20:35:46 -0800662 mNetInitiatedListener,
663 mSuplEsEnabled);
WyattRileyd1309312019-02-28 12:11:45 -0800664 sendMessage(INITIALIZE_HANDLER, 0, null);
Tsuwei Chen3324e952014-09-07 01:30:42 -0700665
Anil Admal75b9fd62018-11-28 11:22:50 -0800666 mGnssStatusListenerHelper = new GnssStatusListenerHelper(mContext, mHandler) {
destradaa6568d702014-10-27 12:47:41 -0700667 @Override
668 protected boolean isAvailableInPlatform() {
destradaa13a60b02015-01-15 18:36:01 -0800669 return isSupported();
destradaa6568d702014-10-27 12:47:41 -0700670 }
671
672 @Override
673 protected boolean isGpsEnabled() {
Yu-Han Yang76f99952019-05-04 17:45:44 -0700674 return GnssLocationProvider.this.isGpsEnabled();
destradaa6568d702014-10-27 12:47:41 -0700675 }
676 };
677
Yu-Han Yang8de21502018-04-23 01:40:25 -0700678 mGnssMeasurementsProvider = new GnssMeasurementsProvider(mContext, mHandler) {
destradaa6568d702014-10-27 12:47:41 -0700679 @Override
680 protected boolean isGpsEnabled() {
Yu-Han Yang76f99952019-05-04 17:45:44 -0700681 return GnssLocationProvider.this.isGpsEnabled();
destradaa6568d702014-10-27 12:47:41 -0700682 }
683 };
684
Anil Admalefd9dc62019-03-12 17:39:20 -0700685 mGnssMeasurementCorrectionsProvider = new GnssMeasurementCorrectionsProvider(mHandler);
686
Anil Admal75b9fd62018-11-28 11:22:50 -0800687 mGnssNavigationMessageProvider = new GnssNavigationMessageProvider(mContext, mHandler) {
destradaa6568d702014-10-27 12:47:41 -0700688 @Override
destradaa6568d702014-10-27 12:47:41 -0700689 protected boolean isGpsEnabled() {
Yu-Han Yang76f99952019-05-04 17:45:44 -0700690 return GnssLocationProvider.this.isGpsEnabled();
destradaa6568d702014-10-27 12:47:41 -0700691 }
692 };
Yu-Han Yanga1862b52018-02-20 17:05:59 -0800693
Anil Admal50ba15e2018-11-01 16:42:42 -0700694 mGnssMetrics = new GnssMetrics(mBatteryStats);
Yu-Han Yang66c7ea92018-03-11 17:17:15 -0700695 mNtpTimeHelper = new NtpTimeHelper(mContext, looper, this);
Soonil Nagarkar35c3b912019-01-31 10:31:24 -0800696 GnssSatelliteBlacklistHelper gnssSatelliteBlacklistHelper =
697 new GnssSatelliteBlacklistHelper(mContext,
698 looper, this);
699 mHandler.post(gnssSatelliteBlacklistHelper::updateSatelliteBlacklist);
Yu-Han Yang3557cc72018-03-21 12:48:36 -0700700 mGnssBatchingProvider = new GnssBatchingProvider();
Yu-Han Yang6dc9f052018-12-04 17:11:24 -0800701 mGnssGeofenceProvider = new GnssGeofenceProvider();
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400702
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700703 mContext.registerReceiverAsUser(new BroadcastReceiver() {
704 @Override
705 public void onReceive(Context context, Intent intent) {
706 if (getSendingUserId() == UserHandle.USER_ALL) {
Soonil Nagarkar35c3b912019-01-31 10:31:24 -0800707 mShutdown = true;
708 updateEnabled();
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700709 }
710 }
Soonil Nagarkar35c3b912019-01-31 10:31:24 -0800711 }, UserHandle.ALL, new IntentFilter(Intent.ACTION_SHUTDOWN), null, mHandler);
712
713 mContext.getContentResolver().registerContentObserver(
714 Settings.Secure.getUriFor(Settings.Secure.LOCATION_MODE),
715 true,
716 new ContentObserver(mHandler) {
717 @Override
718 public void onChange(boolean selfChange) {
719 updateEnabled();
720 }
721 }, UserHandle.USER_ALL);
Mike Lockwoodd03ff942010-02-09 08:46:14 -0500722
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700723 setProperties(PROPERTIES);
Soonil Nagarkar90da1ab2019-01-04 16:26:59 -0800724 setEnabled(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 }
726
Yu-Han Yanga1862b52018-02-20 17:05:59 -0800727 /**
728 * Implements {@link InjectNtpTimeCallback#injectTime}
729 */
730 @Override
731 public void injectTime(long time, long timeReference, int uncertainty) {
732 native_inject_time(time, timeReference, uncertainty);
733 }
734
Anil Admal50ba15e2018-11-01 16:42:42 -0700735 /**
736 * Implements {@link GnssNetworkConnectivityHandler.GnssNetworkListener#onNetworkAvailable()}
737 */
738 private void onNetworkAvailable() {
739 mNtpTimeHelper.onNetworkAvailable();
Kevin Tang8c6ac672019-03-22 12:31:01 -0700740 if (mDownloadPsdsDataPending == STATE_PENDING_NETWORK) {
741 if (mSupportsPsds) {
Anil Admal316f9482019-02-12 18:57:18 -0800742 // Download only if supported, (prevents an unnecessary on-boot download)
Kevin Tang8c6ac672019-03-22 12:31:01 -0700743 psdsDownloadRequest();
destradaaef752b62015-04-17 13:10:47 -0700744 }
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400745 }
746 }
Yu-Han Yang8de21502018-04-23 01:40:25 -0700747
Yu-Han Yang53f4d6d2019-02-13 21:47:41 -0800748 private void handleRequestLocation(boolean independentFromGnss, boolean isUserEmergency) {
Yu-Han Yange7baef32018-02-09 13:58:17 -0800749 if (isRequestLocationRateLimited()) {
750 if (DEBUG) {
751 Log.d(TAG, "RequestLocation is denied due to too frequent requests.");
752 }
753 return;
754 }
Yu-Han Yang74041ff2018-04-06 15:57:31 -0700755 ContentResolver resolver = mContext.getContentResolver();
756 long durationMillis = Settings.Global.getLong(
757 resolver,
758 Settings.Global.GNSS_HAL_LOCATION_REQUEST_DURATION_MILLIS,
759 LOCATION_UPDATE_DURATION_MILLIS);
760 if (durationMillis == 0) {
761 Log.i(TAG, "GNSS HAL location request is disabled by Settings.");
762 return;
763 }
Yu-Han Yange7baef32018-02-09 13:58:17 -0800764
765 LocationManager locationManager = (LocationManager) mContext.getSystemService(
766 Context.LOCATION_SERVICE);
Yu-Han Yang07561382018-02-21 13:08:37 -0800767 String provider;
768 LocationChangeListener locationListener;
Anil Admalb1c6c0d2019-06-20 12:00:16 -0700769 LocationRequest locationRequest = new LocationRequest()
770 .setInterval(LOCATION_UPDATE_MIN_TIME_INTERVAL_MILLIS)
771 .setFastestInterval(LOCATION_UPDATE_MIN_TIME_INTERVAL_MILLIS);
Yu-Han Yange7baef32018-02-09 13:58:17 -0800772
773 if (independentFromGnss) {
774 // For fast GNSS TTFF
Yu-Han Yang07561382018-02-21 13:08:37 -0800775 provider = LocationManager.NETWORK_PROVIDER;
776 locationListener = mNetworkLocationListener;
Anil Admalb1c6c0d2019-06-20 12:00:16 -0700777 locationRequest.setQuality(LocationRequest.POWER_LOW);
Yu-Han Yange7baef32018-02-09 13:58:17 -0800778 } else {
779 // For Device-Based Hybrid (E911)
Yu-Han Yang07561382018-02-21 13:08:37 -0800780 provider = LocationManager.FUSED_PROVIDER;
781 locationListener = mFusedLocationListener;
Anil Admalb1c6c0d2019-06-20 12:00:16 -0700782 locationRequest.setQuality(LocationRequest.ACCURACY_FINE);
783 }
784
785 locationRequest.setProvider(provider);
786
787 // Ignore location settings if in emergency mode.
788 if (isUserEmergency && mNIHandler.getInEmergency()) {
789 locationRequest.setLocationSettingsIgnored(true);
790 durationMillis *= EMERGENCY_LOCATION_UPDATE_DURATION_MULTIPLIER;
Yu-Han Yange7baef32018-02-09 13:58:17 -0800791 }
Yu-Han Yang07561382018-02-21 13:08:37 -0800792
793 Log.i(TAG,
Yu-Han Yang74041ff2018-04-06 15:57:31 -0700794 String.format(
795 "GNSS HAL Requesting location updates from %s provider for %d millis.",
796 provider, durationMillis));
Yu-Han Yang53f4d6d2019-02-13 21:47:41 -0800797
Yu-Han Yange684dda2018-05-24 10:29:39 -0700798 try {
Yu-Han Yang53f4d6d2019-02-13 21:47:41 -0800799 locationManager.requestLocationUpdates(locationRequest,
Yu-Han Yange684dda2018-05-24 10:29:39 -0700800 locationListener, mHandler.getLooper());
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700801 locationListener.mNumLocationUpdateRequest++;
Yu-Han Yange684dda2018-05-24 10:29:39 -0700802 mHandler.postDelayed(() -> {
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700803 if (--locationListener.mNumLocationUpdateRequest == 0) {
Yu-Han Yange684dda2018-05-24 10:29:39 -0700804 Log.i(TAG,
805 String.format("Removing location updates from %s provider.", provider));
806 locationManager.removeUpdates(locationListener);
807 }
808 }, durationMillis);
809 } catch (IllegalArgumentException e) {
810 Log.w(TAG, "Unable to request location.", e);
811 }
Yu-Han Yange7baef32018-02-09 13:58:17 -0800812 }
813
814 private void injectBestLocation(Location location) {
Anil Admalb1c6c0d2019-06-20 12:00:16 -0700815 if (DEBUG) {
816 Log.d(TAG, "injectBestLocation: " + location);
817 }
Yu-Han Yange7baef32018-02-09 13:58:17 -0800818 int gnssLocationFlags = LOCATION_HAS_LAT_LONG |
819 (location.hasAltitude() ? LOCATION_HAS_ALTITUDE : 0) |
820 (location.hasSpeed() ? LOCATION_HAS_SPEED : 0) |
821 (location.hasBearing() ? LOCATION_HAS_BEARING : 0) |
822 (location.hasAccuracy() ? LOCATION_HAS_HORIZONTAL_ACCURACY : 0) |
823 (location.hasVerticalAccuracy() ? LOCATION_HAS_VERTICAL_ACCURACY : 0) |
824 (location.hasSpeedAccuracy() ? LOCATION_HAS_SPEED_ACCURACY : 0) |
825 (location.hasBearingAccuracy() ? LOCATION_HAS_BEARING_ACCURACY : 0);
826
827 double latitudeDegrees = location.getLatitude();
828 double longitudeDegrees = location.getLongitude();
829 double altitudeMeters = location.getAltitude();
830 float speedMetersPerSec = location.getSpeed();
831 float bearingDegrees = location.getBearing();
832 float horizontalAccuracyMeters = location.getAccuracy();
833 float verticalAccuracyMeters = location.getVerticalAccuracyMeters();
834 float speedAccuracyMetersPerSecond = location.getSpeedAccuracyMetersPerSecond();
835 float bearingAccuracyDegrees = location.getBearingAccuracyDegrees();
836 long timestamp = location.getTime();
Pierre Fite-Georgelb50cdaf2019-02-25 15:42:45 -0800837
Pierre Fite-Georgel9e96c572019-02-25 16:12:53 -0800838 int elapsedRealtimeFlags = ELAPSED_REALTIME_HAS_TIMESTAMP_NS
839 | (location.hasElapsedRealtimeUncertaintyNanos()
Sasha Kuznetsov24da7f92019-11-01 12:21:50 -0700840 ? ELAPSED_REALTIME_HAS_TIME_UNCERTAINTY_NS : 0);
Pierre Fite-Georgelb50cdaf2019-02-25 15:42:45 -0800841 long elapsedRealtimeNanos = location.getElapsedRealtimeNanos();
Yu-Han Yang3cd9a862019-03-25 17:00:03 -0700842 double elapsedRealtimeUncertaintyNanos = location.getElapsedRealtimeUncertaintyNanos();
Pierre Fite-Georgelb50cdaf2019-02-25 15:42:45 -0800843
844 native_inject_best_location(
845 gnssLocationFlags, latitudeDegrees, longitudeDegrees,
846 altitudeMeters, speedMetersPerSec, bearingDegrees,
847 horizontalAccuracyMeters, verticalAccuracyMeters,
848 speedAccuracyMetersPerSecond, bearingAccuracyDegrees, timestamp,
Pierre Fite-Georgel9e96c572019-02-25 16:12:53 -0800849 elapsedRealtimeFlags, elapsedRealtimeNanos, elapsedRealtimeUncertaintyNanos);
Yu-Han Yange7baef32018-02-09 13:58:17 -0800850 }
851
Yu-Han Yange7baef32018-02-09 13:58:17 -0800852 /** Returns true if the location request is too frequent. */
853 private boolean isRequestLocationRateLimited() {
Anil Admal316f9482019-02-12 18:57:18 -0800854 // TODO: implement exponential backoff.
Yu-Han Yange7baef32018-02-09 13:58:17 -0800855 return false;
856 }
857
Kevin Tang8c6ac672019-03-22 12:31:01 -0700858 private void handleDownloadPsdsData() {
859 if (!mSupportsPsds) {
860 // native code reports psds not supported, don't try
861 Log.d(TAG, "handleDownloadPsdsData() called when PSDS not supported");
Wyatt Riley0d6e54e22016-10-05 12:03:03 -0700862 return;
863 }
Kevin Tang8c6ac672019-03-22 12:31:01 -0700864 if (mDownloadPsdsDataPending == STATE_DOWNLOADING) {
Kevin Tang40e1baf2012-01-10 14:32:44 -0800865 // already downloading data
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400866 return;
867 }
Anil Admal50ba15e2018-11-01 16:42:42 -0700868 if (!mNetworkConnectivityHandler.isDataNetworkConnected()) {
Kevin Tang40e1baf2012-01-10 14:32:44 -0800869 // try again when network is up
Kevin Tang8c6ac672019-03-22 12:31:01 -0700870 mDownloadPsdsDataPending = STATE_PENDING_NETWORK;
Kevin Tang40e1baf2012-01-10 14:32:44 -0800871 return;
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400872 }
Kevin Tang8c6ac672019-03-22 12:31:01 -0700873 mDownloadPsdsDataPending = STATE_DOWNLOADING;
Kevin Tang40e1baf2012-01-10 14:32:44 -0800874
Yu-Han Yang76f99952019-05-04 17:45:44 -0700875 synchronized (mLock) {
876 // hold wake lock while task runs
877 mDownloadPsdsWakeLock.acquire(DOWNLOAD_PSDS_DATA_TIMEOUT_MS);
878 }
Kevin Tang8c6ac672019-03-22 12:31:01 -0700879 Log.i(TAG, "WakeLock acquired by handleDownloadPsdsData()");
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700880 AsyncTask.THREAD_POOL_EXECUTOR.execute(() -> {
Kevin Tang8c6ac672019-03-22 12:31:01 -0700881 GpsPsdsDownloader psdsDownloader = new GpsPsdsDownloader(
Anil Admald71cf142018-12-21 14:59:36 -0800882 mGnssConfiguration.getProperties());
Kevin Tang8c6ac672019-03-22 12:31:01 -0700883 byte[] data = psdsDownloader.downloadPsdsData();
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700884 if (data != null) {
Kevin Tang8c6ac672019-03-22 12:31:01 -0700885 if (DEBUG) Log.d(TAG, "calling native_inject_psds_data");
886 native_inject_psds_data(data, data.length);
887 mPsdsBackOff.reset();
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700888 }
Kevin Tang40e1baf2012-01-10 14:32:44 -0800889
Kevin Tang8c6ac672019-03-22 12:31:01 -0700890 sendMessage(DOWNLOAD_PSDS_DATA_FINISHED, 0, null);
Kevin Tang40e1baf2012-01-10 14:32:44 -0800891
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700892 if (data == null) {
893 // try again later
894 // since this is delayed and not urgent we do not hold a wake lock here
Kevin Tang8c6ac672019-03-22 12:31:01 -0700895 mHandler.sendEmptyMessageDelayed(DOWNLOAD_PSDS_DATA,
896 mPsdsBackOff.nextBackoffMillis());
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700897 }
Kevin Tang40e1baf2012-01-10 14:32:44 -0800898
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700899 // Release wake lock held by task, synchronize on mLock in case multiple
900 // download tasks overrun.
901 synchronized (mLock) {
Kevin Tang8c6ac672019-03-22 12:31:01 -0700902 if (mDownloadPsdsWakeLock.isHeld()) {
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700903 // This wakelock may have time-out, if a timeout was specified.
904 // Catch (and ignore) any timeout exceptions.
Yu-Han Yang499a6ba2019-11-14 14:19:13 -0800905 mDownloadPsdsWakeLock.release();
906 if (DEBUG) Log.d(TAG, "WakeLock released by handleDownloadPsdsData()");
Soonil Nagarkar1575a042018-10-24 17:54:54 -0700907 } else {
908 Log.e(TAG, "WakeLock expired before release in "
Kevin Tang8c6ac672019-03-22 12:31:01 -0700909 + "handleDownloadPsdsData()");
Wei Wangc5706f62017-04-18 11:26:26 -0700910 }
Jeff Brown028872f2012-08-25 13:07:01 -0700911 }
Kevin Tang40e1baf2012-01-10 14:32:44 -0800912 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 }
914
Anil Admal2ac70462019-06-28 19:17:41 -0700915 private void injectLocation(Location location) {
Mike Lockwoodd26ce0d2009-06-11 12:25:46 -0400916 if (location.hasAccuracy()) {
Anil Admalb1c6c0d2019-06-20 12:00:16 -0700917 if (DEBUG) {
918 Log.d(TAG, "injectLocation: " + location);
919 }
Mike Lockwoodd26ce0d2009-06-11 12:25:46 -0400920 native_inject_location(location.getLatitude(), location.getLongitude(),
921 location.getAccuracy());
922 }
Mike Lockwoodfd6e5f02009-05-21 11:28:20 -0400923 }
924
Anil Admald71cf142018-12-21 14:59:36 -0800925 private void setSuplHostPort() {
926 mSuplServerHost = mGnssConfiguration.getSuplHost();
927 mSuplServerPort = mGnssConfiguration.getSuplPort(TCP_MIN_PORT);
Tsuwei Chen678c13c2014-09-22 17:48:41 -0700928 if (mSuplServerHost != null
929 && mSuplServerPort > TCP_MIN_PORT
930 && mSuplServerPort <= TCP_MAX_PORT) {
Anil Admalc70344b2018-11-16 14:22:38 -0800931 native_set_agps_server(GnssNetworkConnectivityHandler.AGPS_TYPE_SUPL,
932 mSuplServerHost, mSuplServerPort);
Tsuwei Chen678c13c2014-09-22 17:48:41 -0700933 }
Tsuwei Chen52617bb2014-08-25 11:49:11 -0700934 }
935
Tsuwei Chen462bcd82014-09-17 12:28:49 -0700936 /**
937 * Checks what SUPL mode to use, according to the AGPS mode as well as the
938 * allowed mode from properties.
939 *
Tsuwei Chen462bcd82014-09-17 12:28:49 -0700940 * @param agpsEnabled whether AGPS is enabled by settings value
Tsuwei Chen462bcd82014-09-17 12:28:49 -0700941 * @return SUPL mode (MSA vs MSB vs STANDALONE)
942 */
Yu-Han Yang6a5f0b72019-01-24 18:34:28 -0800943 private int getSuplMode(boolean agpsEnabled) {
Tsuwei Chen462bcd82014-09-17 12:28:49 -0700944 if (agpsEnabled) {
Anil Admald71cf142018-12-21 14:59:36 -0800945 int suplMode = mGnssConfiguration.getSuplMode(0);
946 if (suplMode == 0) {
947 return GPS_POSITION_MODE_STANDALONE;
Tsuwei Chen462bcd82014-09-17 12:28:49 -0700948 }
Anil Admald71cf142018-12-21 14:59:36 -0800949
destradaabfb3bdb2015-04-29 14:42:35 -0700950 // MS-Based is the preferred mode for Assisted-GPS position computation, so we favor
951 // such mode when it is available
952 if (hasCapability(GPS_CAPABILITY_MSB) && (suplMode & AGPS_SUPL_MODE_MSB) != 0) {
953 return GPS_POSITION_MODE_MS_BASED;
954 }
Tsuwei Chen462bcd82014-09-17 12:28:49 -0700955 }
956 return GPS_POSITION_MODE_STANDALONE;
957 }
958
Yu-Han Yang76f99952019-05-04 17:45:44 -0700959 private void setGpsEnabled(boolean enabled) {
960 synchronized (mLock) {
961 mGpsEnabled = enabled;
962 }
963 }
964
965 private void handleEnable() {
966 if (DEBUG) Log.d(TAG, "handleEnable");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967
Soonil Nagarkar35c3b912019-01-31 10:31:24 -0800968 boolean inited = native_init();
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700969
Soonil Nagarkar35c3b912019-01-31 10:31:24 -0800970 if (inited) {
Yu-Han Yang76f99952019-05-04 17:45:44 -0700971 setGpsEnabled(true);
Kevin Tang8c6ac672019-03-22 12:31:01 -0700972 mSupportsPsds = native_supports_psds();
Tsuwei Chen678c13c2014-09-22 17:48:41 -0700973
974 // TODO: remove the following native calls if we can make sure they are redundant.
Mike Lockwood734d6032009-07-28 18:30:25 -0700975 if (mSuplServerHost != null) {
Anil Admalc70344b2018-11-16 14:22:38 -0800976 native_set_agps_server(GnssNetworkConnectivityHandler.AGPS_TYPE_SUPL,
977 mSuplServerHost, mSuplServerPort);
Mike Lockwood734d6032009-07-28 18:30:25 -0700978 }
979 if (mC2KServerHost != null) {
Anil Admalc70344b2018-11-16 14:22:38 -0800980 native_set_agps_server(GnssNetworkConnectivityHandler.AGPS_TYPE_C2K,
981 mC2KServerHost, mC2KServerPort);
Mike Lockwood734d6032009-07-28 18:30:25 -0700982 }
destradaa13a60b02015-01-15 18:36:01 -0800983
Lifu Tang818aa2c2016-02-01 01:52:00 -0800984 mGnssMeasurementsProvider.onGpsEnabledChanged();
985 mGnssNavigationMessageProvider.onGpsEnabledChanged();
Yu-Han Yang3557cc72018-03-21 12:48:36 -0700986 mGnssBatchingProvider.enable();
Anil Admal138cdc32019-04-16 10:07:43 -0700987 if (mGnssVisibilityControl != null) {
Anil Admal8b83dc12019-06-12 13:55:42 -0700988 mGnssVisibilityControl.onGpsEnabledChanged(/* isEnabled= */ true);
Anil Admal138cdc32019-04-16 10:07:43 -0700989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 } else {
Yu-Han Yang76f99952019-05-04 17:45:44 -0700991 setGpsEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 Log.w(TAG, "Failed to enable location provider");
993 }
994 }
995
Yu-Han Yang76f99952019-05-04 17:45:44 -0700996 private void handleDisable() {
997 if (DEBUG) Log.d(TAG, "handleDisable");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998
Yu-Han Yang76f99952019-05-04 17:45:44 -0700999 setGpsEnabled(false);
David Christie3bc26142013-12-19 14:53:44 -08001000 updateClientUids(new WorkSource());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 stopNavigating();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001002 mAlarmManager.cancel(mWakeupIntent);
1003 mAlarmManager.cancel(mTimeoutIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004
Anil Admal138cdc32019-04-16 10:07:43 -07001005 if (mGnssVisibilityControl != null) {
Yu-Han Yang76f99952019-05-04 17:45:44 -07001006 mGnssVisibilityControl.onGpsEnabledChanged(/* isEnabled= */ false);
Anil Admal138cdc32019-04-16 10:07:43 -07001007 }
Yu-Han Yang3557cc72018-03-21 12:48:36 -07001008 mGnssBatchingProvider.disable();
Mike Lockwoodcf1d8cb2010-01-20 10:14:54 -05001009 // do this before releasing wakelock
1010 native_cleanup();
destradaa13a60b02015-01-15 18:36:01 -08001011
Lifu Tang818aa2c2016-02-01 01:52:00 -08001012 mGnssMeasurementsProvider.onGpsEnabledChanged();
1013 mGnssNavigationMessageProvider.onGpsEnabledChanged();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 }
1015
Soonil Nagarkar35c3b912019-01-31 10:31:24 -08001016 private void updateEnabled() {
Tyler Trephan037ef9d2019-05-17 13:41:18 -07001017 // Generally follow location setting for current user
1018 boolean enabled = mContext.getSystemService(LocationManager.class)
1019 .isLocationEnabledForUser(UserHandle.CURRENT);
WyattRileyb2446072019-03-01 07:41:49 -08001020
Yu-Han Yang76f99952019-05-04 17:45:44 -07001021 // ... but disable if PowerManager overrides
1022 enabled &= !mDisableGpsForPowerManager;
WyattRileyb2446072019-03-01 07:41:49 -08001023
Yu-Han Yang76f99952019-05-04 17:45:44 -07001024 // .. but enable anyway, if there's an active settings-ignored request (e.g. ELS)
1025 enabled |= (mProviderRequest != null && mProviderRequest.reportLocation
Sasha Kuznetsov24da7f92019-11-01 12:21:50 -07001026 && mProviderRequest.locationSettingsIgnored);
WyattRileyb2446072019-03-01 07:41:49 -08001027
Yu-Han Yang76f99952019-05-04 17:45:44 -07001028 // ... and, finally, disable anyway, if device is being shut down
1029 enabled &= !mShutdown;
WyattRileyb2446072019-03-01 07:41:49 -08001030
Yu-Han Yang76f99952019-05-04 17:45:44 -07001031 if (enabled == isGpsEnabled()) {
1032 return;
1033 }
Soonil Nagarkar35c3b912019-01-31 10:31:24 -08001034
Yu-Han Yang76f99952019-05-04 17:45:44 -07001035 if (enabled) {
1036 handleEnable();
1037 } else {
1038 handleDisable();
Soonil Nagarkar35c3b912019-01-31 10:31:24 -08001039 }
1040 }
1041
Yu-Han Yang76f99952019-05-04 17:45:44 -07001042 private boolean isGpsEnabled() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001043 synchronized (mLock) {
Yu-Han Yang76f99952019-05-04 17:45:44 -07001044 return mGpsEnabled;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001045 }
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001046 }
1047
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001048 @Override
Soonil Nagarkard334f7b2019-07-08 16:16:19 -07001049 public void onSetRequest(ProviderRequest request, WorkSource source) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001050 sendMessage(SET_REQUEST, 0, new GpsRequest(request, source));
Mike Lockwood62a8fc12010-03-22 14:23:26 -04001051 }
1052
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001053 private void handleSetRequest(ProviderRequest request, WorkSource source) {
David Christied4edf4c2014-08-12 15:22:27 -07001054 mProviderRequest = request;
1055 mWorkSource = source;
Soonil Nagarkar35c3b912019-01-31 10:31:24 -08001056 updateEnabled();
David Christied4edf4c2014-08-12 15:22:27 -07001057 updateRequirements();
1058 }
1059
1060 // Called when the requirements for GPS may have changed
1061 private void updateRequirements() {
1062 if (mProviderRequest == null || mWorkSource == null) {
1063 return;
1064 }
1065
David Christied4edf4c2014-08-12 15:22:27 -07001066 if (DEBUG) Log.d(TAG, "setRequest " + mProviderRequest);
Yu-Han Yang76f99952019-05-04 17:45:44 -07001067 if (mProviderRequest.reportLocation && isGpsEnabled()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001068 // update client uids
David Christied4edf4c2014-08-12 15:22:27 -07001069 updateClientUids(mWorkSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070
David Christied4edf4c2014-08-12 15:22:27 -07001071 mFixInterval = (int) mProviderRequest.interval;
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001072 mLowPowerMode = mProviderRequest.lowPowerMode;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001073 // check for overflow
David Christied4edf4c2014-08-12 15:22:27 -07001074 if (mFixInterval != mProviderRequest.interval) {
1075 Log.w(TAG, "interval overflow: " + mProviderRequest.interval);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001076 mFixInterval = Integer.MAX_VALUE;
1077 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001078
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001079 // apply request to GPS engine
Mike Lockwood04598b62010-04-14 17:17:24 -04001080 if (mStarted && hasCapability(GPS_CAPABILITY_SCHEDULING)) {
gomo48f1a642017-11-10 20:35:46 -08001081 // change period and/or lowPowerMode
Yu-Han Yangc8b9ff72018-04-17 00:47:24 -07001082 if (!setPositionMode(mPositionMode, GPS_POSITION_RECURRENCE_PERIODIC,
gomo48f1a642017-11-10 20:35:46 -08001083 mFixInterval, 0, 0, mLowPowerMode)) {
1084 Log.e(TAG, "set_position_mode failed in updateRequirements");
Mike Lockwood04598b62010-04-14 17:17:24 -04001085 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001086 } else if (!mStarted) {
1087 // start GPS
Yu-Han Yang6a5f0b72019-01-24 18:34:28 -08001088 startNavigating();
gomo300b2402017-12-13 19:04:12 -08001089 } else {
1090 // GNSS Engine is already ON, but no GPS_CAPABILITY_SCHEDULING
1091 mAlarmManager.cancel(mTimeoutIntent);
1092 if (mFixInterval >= NO_FIX_TIMEOUT) {
1093 // set timer to give up if we do not receive a fix within NO_FIX_TIMEOUT
1094 // and our fix interval is not short
1095 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001096 SystemClock.elapsedRealtime() + NO_FIX_TIMEOUT, mTimeoutIntent);
1097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001099 } else {
Dianne Hackborn002a54e2013-01-10 17:34:55 -08001100 updateClientUids(new WorkSource());
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001101
1102 stopNavigating();
1103 mAlarmManager.cancel(mWakeupIntent);
1104 mAlarmManager.cancel(mTimeoutIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 }
1106 }
1107
Yu-Han Yangc8b9ff72018-04-17 00:47:24 -07001108 private boolean setPositionMode(int mode, int recurrence, int minInterval,
1109 int preferredAccuracy, int preferredTime, boolean lowPowerMode) {
1110 GnssPositionMode positionMode = new GnssPositionMode(mode, recurrence, minInterval,
1111 preferredAccuracy, preferredTime, lowPowerMode);
1112 if (mLastPositionMode != null && mLastPositionMode.equals(positionMode)) {
1113 return true;
1114 }
1115
1116 boolean result = native_set_position_mode(mode, recurrence, minInterval,
1117 preferredAccuracy, preferredTime, lowPowerMode);
1118 if (result) {
1119 mLastPositionMode = positionMode;
1120 } else {
1121 mLastPositionMode = null;
1122 }
1123 return result;
1124 }
1125
Dianne Hackborn002a54e2013-01-10 17:34:55 -08001126 private void updateClientUids(WorkSource source) {
Narayan Kamath32684dd2018-01-08 17:32:51 +00001127 if (source.equals(mClientSource)) {
Victoria Leaseea78b852013-01-15 10:39:28 -08001128 return;
1129 }
Dianne Hackborn002a54e2013-01-10 17:34:55 -08001130
Narayan Kamath32684dd2018-01-08 17:32:51 +00001131 // (1) Inform BatteryStats that the list of IDs we're tracking changed.
1132 try {
1133 mBatteryStats.noteGpsChanged(mClientSource, source);
1134 } catch (RemoteException e) {
1135 Log.w(TAG, "RemoteException", e);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001136 }
1137
Narayan Kamath32684dd2018-01-08 17:32:51 +00001138 // (2) Inform AppOps service about the list of changes to UIDs.
1139
1140 List<WorkChain>[] diffs = WorkSource.diffChains(mClientSource, source);
1141 if (diffs != null) {
1142 List<WorkChain> newChains = diffs[0];
1143 List<WorkChain> goneChains = diffs[1];
1144
1145 if (newChains != null) {
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001146 for (WorkChain newChain : newChains) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001147 mAppOps.startOpNoThrow(AppOpsManager.OP_GPS, newChain.getAttributionUid(),
1148 newChain.getAttributionTag());
Narayan Kamath32684dd2018-01-08 17:32:51 +00001149 }
1150 }
1151
1152 if (goneChains != null) {
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001153 for (WorkChain goneChain : goneChains) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001154 mAppOps.finishOp(AppOpsManager.OP_GPS, goneChain.getAttributionUid(),
1155 goneChain.getAttributionTag());
Narayan Kamath32684dd2018-01-08 17:32:51 +00001156 }
1157 }
1158
1159 mClientSource.transferWorkChains(source);
1160 }
1161
1162 // Update the flat UIDs and names list and inform app-ops of all changes.
1163 WorkSource[] changes = mClientSource.setReturningDiffs(source);
1164 if (changes != null) {
1165 WorkSource newWork = changes[0];
1166 WorkSource goneWork = changes[1];
1167
1168 // Update sources that were not previously tracked.
1169 if (newWork != null) {
1170 for (int i = 0; i < newWork.size(); i++) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001171 mAppOps.startOpNoThrow(AppOpsManager.OP_GPS,
1172 newWork.get(i), newWork.getName(i));
Narayan Kamath32684dd2018-01-08 17:32:51 +00001173 }
1174 }
1175
1176 // Update sources that are no longer tracked.
1177 if (goneWork != null) {
1178 for (int i = 0; i < goneWork.size(); i++) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001179 mAppOps.finishOp(AppOpsManager.OP_GPS, goneWork.get(i), goneWork.getName(i));
Dianne Hackborn2e418422009-06-22 20:00:17 -07001180 }
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001181 }
1182 }
1183 }
1184
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001185 @Override
Soonil Nagarkard334f7b2019-07-08 16:16:19 -07001186 public void onSendExtraCommand(int uid, int pid, String command, Bundle extras) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001187
Mike Lockwood63aa5a62010-04-14 19:21:31 -04001188 long identity = Binder.clearCallingIdentity();
Peter Visontayb25db362017-11-01 18:18:12 +00001189 try {
Peter Visontayb25db362017-11-01 18:18:12 +00001190 if ("delete_aiding_data".equals(command)) {
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001191 deleteAidingData(extras);
Peter Visontayb25db362017-11-01 18:18:12 +00001192 } else if ("force_time_injection".equals(command)) {
1193 requestUtcTime();
Kevin Tang8c6ac672019-03-22 12:31:01 -07001194 } else if ("force_psds_injection".equals(command)) {
1195 if (mSupportsPsds) {
1196 psdsDownloadRequest();
Peter Visontayb25db362017-11-01 18:18:12 +00001197 }
1198 } else {
1199 Log.w(TAG, "sendExtraCommand: unknown command " + command);
Mike Lockwood93bc44d2009-05-20 16:58:22 -04001200 }
Peter Visontayb25db362017-11-01 18:18:12 +00001201 } finally {
1202 Binder.restoreCallingIdentity(identity);
Mike Lockwood93bc44d2009-05-20 16:58:22 -04001203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 }
1205
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001206 private void deleteAidingData(Bundle extras) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 int flags;
1208
1209 if (extras == null) {
1210 flags = GPS_DELETE_ALL;
1211 } else {
1212 flags = 0;
1213 if (extras.getBoolean("ephemeris")) flags |= GPS_DELETE_EPHEMERIS;
1214 if (extras.getBoolean("almanac")) flags |= GPS_DELETE_ALMANAC;
1215 if (extras.getBoolean("position")) flags |= GPS_DELETE_POSITION;
1216 if (extras.getBoolean("time")) flags |= GPS_DELETE_TIME;
1217 if (extras.getBoolean("iono")) flags |= GPS_DELETE_IONO;
1218 if (extras.getBoolean("utc")) flags |= GPS_DELETE_UTC;
1219 if (extras.getBoolean("health")) flags |= GPS_DELETE_HEALTH;
1220 if (extras.getBoolean("svdir")) flags |= GPS_DELETE_SVDIR;
1221 if (extras.getBoolean("svsteer")) flags |= GPS_DELETE_SVSTEER;
1222 if (extras.getBoolean("sadata")) flags |= GPS_DELETE_SADATA;
1223 if (extras.getBoolean("rti")) flags |= GPS_DELETE_RTI;
1224 if (extras.getBoolean("celldb-info")) flags |= GPS_DELETE_CELLDB_INFO;
1225 if (extras.getBoolean("all")) flags |= GPS_DELETE_ALL;
1226 }
1227
1228 if (flags != 0) {
1229 native_delete_aiding_data(flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 }
1232
Yu-Han Yang6a5f0b72019-01-24 18:34:28 -08001233 private void startNavigating() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 if (!mStarted) {
Yu-Han Yang6a5f0b72019-01-24 18:34:28 -08001235 if (DEBUG) Log.d(TAG, "startNavigating");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001236 mTimeToFirstFix = 0;
1237 mLastFixTime = 0;
WyattRileyba6072f2019-04-18 07:37:52 -07001238 setStarted(true);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001239 mPositionMode = GPS_POSITION_MODE_STANDALONE;
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001240 // Notify about suppressed output, if speed limit was previously exceeded.
1241 // Elsewhere, we check again with every speed output reported.
1242 if (mItarSpeedLimitExceeded) {
1243 Log.i(TAG, "startNavigating with ITAR limit in place. Output limited " +
1244 "until slow enough speed reported.");
1245 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001246
Tsuwei Chen462bcd82014-09-17 12:28:49 -07001247 boolean agpsEnabled =
1248 (Settings.Global.getInt(mContext.getContentResolver(),
gomo48f1a642017-11-10 20:35:46 -08001249 Settings.Global.ASSISTED_GPS_ENABLED, 1) != 0);
Yu-Han Yang6a5f0b72019-01-24 18:34:28 -08001250 mPositionMode = getSuplMode(agpsEnabled);
Mike Lockwoodbcab8df2009-06-25 16:39:09 -04001251
Stan Chesnutt1d72d8c2013-04-15 19:18:02 -07001252 if (DEBUG) {
1253 String mode;
1254
gomo48f1a642017-11-10 20:35:46 -08001255 switch (mPositionMode) {
Stan Chesnutt1d72d8c2013-04-15 19:18:02 -07001256 case GPS_POSITION_MODE_STANDALONE:
1257 mode = "standalone";
1258 break;
1259 case GPS_POSITION_MODE_MS_ASSISTED:
1260 mode = "MS_ASSISTED";
1261 break;
1262 case GPS_POSITION_MODE_MS_BASED:
1263 mode = "MS_BASED";
1264 break;
1265 default:
1266 mode = "unknown";
1267 break;
1268 }
1269 Log.d(TAG, "setting position_mode to " + mode);
1270 }
1271
Mike Lockwood04598b62010-04-14 17:17:24 -04001272 int interval = (hasCapability(GPS_CAPABILITY_SCHEDULING) ? mFixInterval : 1000);
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001273 mLowPowerMode = mProviderRequest.lowPowerMode;
Yu-Han Yangc8b9ff72018-04-17 00:47:24 -07001274 if (!setPositionMode(mPositionMode, GPS_POSITION_RECURRENCE_PERIODIC,
gomo48f1a642017-11-10 20:35:46 -08001275 interval, 0, 0, mLowPowerMode)) {
WyattRileyba6072f2019-04-18 07:37:52 -07001276 setStarted(false);
Mike Lockwood04598b62010-04-14 17:17:24 -04001277 Log.e(TAG, "set_position_mode failed in startNavigating()");
1278 return;
1279 }
1280 if (!native_start()) {
WyattRileyba6072f2019-04-18 07:37:52 -07001281 setStarted(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 Log.e(TAG, "native_start failed in startNavigating()");
Mike Lockwood0632ca72009-05-14 15:51:03 -04001283 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 }
1285
1286 // reset SV count to zero
Wyatt Rileyc7067412018-02-07 15:50:35 -08001287 mLocationExtras.reset();
Yipeng Cao282b5942017-05-17 20:31:39 -07001288 mFixRequestTime = SystemClock.elapsedRealtime();
Mike Lockwood04598b62010-04-14 17:17:24 -04001289 if (!hasCapability(GPS_CAPABILITY_SCHEDULING)) {
1290 // set timer to give up if we do not receive a fix within NO_FIX_TIMEOUT
1291 // and our fix interval is not short
1292 if (mFixInterval >= NO_FIX_TIMEOUT) {
1293 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1294 SystemClock.elapsedRealtime() + NO_FIX_TIMEOUT, mTimeoutIntent);
1295 }
Mike Lockwood0632ca72009-05-14 15:51:03 -04001296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 }
1298 }
1299
Mike Lockwood62a8fc12010-03-22 14:23:26 -04001300 private void stopNavigating() {
Mike Lockwood29c84342009-05-06 14:01:15 -04001301 if (DEBUG) Log.d(TAG, "stopNavigating");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 if (mStarted) {
WyattRileyba6072f2019-04-18 07:37:52 -07001303 setStarted(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 native_stop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 mLastFixTime = 0;
Yu-Han Yanga50cd602018-08-28 12:33:24 -07001306 // native_stop() may reset the position mode in hardware.
1307 mLastPositionMode = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308
1309 // reset SV count to zero
Wyatt Rileyc7067412018-02-07 15:50:35 -08001310 mLocationExtras.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 }
1312 }
1313
WyattRileyba6072f2019-04-18 07:37:52 -07001314 private void setStarted(boolean started) {
1315 if (mStarted != started) {
1316 mStarted = started;
1317 mStartedChangedElapsedRealtime = SystemClock.elapsedRealtime();
1318 }
1319 }
1320
Mike Lockwood0632ca72009-05-14 15:51:03 -04001321 private void hibernate() {
1322 // stop GPS until our next fix interval arrives
1323 stopNavigating();
Mike Lockwood0632ca72009-05-14 15:51:03 -04001324 mAlarmManager.cancel(mTimeoutIntent);
1325 mAlarmManager.cancel(mWakeupIntent);
1326 long now = SystemClock.elapsedRealtime();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001327 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, now + mFixInterval, mWakeupIntent);
Mike Lockwood04598b62010-04-14 17:17:24 -04001328 }
1329
1330 private boolean hasCapability(int capability) {
Anil Admal312fddb2019-03-25 12:15:43 -07001331 return (mTopHalCapabilities & capability) != 0;
Mike Lockwood0632ca72009-05-14 15:51:03 -04001332 }
1333
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001334 @NativeEntryPoint
Wyatt Riley5d229832017-02-10 17:06:00 -08001335 private void reportLocation(boolean hasLatLong, Location location) {
Wyatt Riley26465d22018-02-12 13:44:24 -08001336 sendMessage(REPORT_LOCATION, hasLatLong ? 1 : 0, location);
1337 }
1338
1339 private void handleReportLocation(boolean hasLatLong, Location location) {
Wyatt Riley5d229832017-02-10 17:06:00 -08001340 if (location.hasSpeed()) {
1341 mItarSpeedLimitExceeded = location.getSpeed() > ITAR_SPEED_LIMIT_METERS_PER_SECOND;
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001342 }
1343
1344 if (mItarSpeedLimitExceeded) {
1345 Log.i(TAG, "Hal reported a speed in excess of ITAR limit." +
1346 " GPS/GNSS Navigation output blocked.");
Siddharth Ray53ddc802018-03-16 12:01:52 -07001347 if (mStarted) {
1348 mGnssMetrics.logReceivedLocationStatus(false);
1349 }
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001350 return; // No output of location allowed
1351 }
1352
Wyatt Riley5d229832017-02-10 17:06:00 -08001353 if (VERBOSE) Log.v(TAG, "reportLocation " + location.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354
Wyatt Riley26465d22018-02-12 13:44:24 -08001355 location.setExtras(mLocationExtras.getBundle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001357 reportLocation(location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358
Siddharth Ray53ddc802018-03-16 12:01:52 -07001359 if (mStarted) {
1360 mGnssMetrics.logReceivedLocationStatus(hasLatLong);
1361 if (hasLatLong) {
1362 if (location.hasAccuracy()) {
1363 mGnssMetrics.logPositionAccuracyMeters(location.getAccuracy());
1364 }
1365 if (mTimeToFirstFix > 0) {
1366 int timeBetweenFixes = (int) (SystemClock.elapsedRealtime() - mLastFixTime);
1367 mGnssMetrics.logMissedReports(mFixInterval, timeBetweenFixes);
1368 }
Siddharth Raybb608c82017-03-16 11:33:34 -07001369 }
WyattRileyba6072f2019-04-18 07:37:52 -07001370 } else {
1371 // Warn or error about long delayed GNSS engine shutdown as this generally wastes
1372 // power and sends location when not expected.
1373 long locationAfterStartedFalseMillis =
1374 SystemClock.elapsedRealtime() - mStartedChangedElapsedRealtime;
1375 if (locationAfterStartedFalseMillis > LOCATION_OFF_DELAY_THRESHOLD_WARN_MILLIS) {
1376 String logMessage = "Unexpected GNSS Location report "
1377 + TimeUtils.formatDuration(locationAfterStartedFalseMillis)
1378 + " after location turned off";
1379 if (locationAfterStartedFalseMillis > LOCATION_OFF_DELAY_THRESHOLD_ERROR_MILLIS) {
1380 Log.e(TAG, logMessage);
1381 } else {
1382 Log.w(TAG, logMessage);
1383 }
1384 }
Siddharth Raybb608c82017-03-16 11:33:34 -07001385 }
1386
Yipeng Cao282b5942017-05-17 20:31:39 -07001387 mLastFixTime = SystemClock.elapsedRealtime();
Hakan Gustavssonfa94ff02010-02-23 09:12:38 +01001388 // report time to first fix
Wyatt Riley5d229832017-02-10 17:06:00 -08001389 if (mTimeToFirstFix == 0 && hasLatLong) {
gomo48f1a642017-11-10 20:35:46 -08001390 mTimeToFirstFix = (int) (mLastFixTime - mFixRequestTime);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001391 if (DEBUG) Log.d(TAG, "TTFF: " + mTimeToFirstFix);
Siddharth Ray53ddc802018-03-16 12:01:52 -07001392 if (mStarted) {
1393 mGnssMetrics.logTimeToFirstFixMilliSecs(mTimeToFirstFix);
1394 }
Hakan Gustavssonfa94ff02010-02-23 09:12:38 +01001395
1396 // notify status listeners
Anil Admal75b9fd62018-11-28 11:22:50 -08001397 mGnssStatusListenerHelper.onFirstFix(mTimeToFirstFix);
Hakan Gustavssonfa94ff02010-02-23 09:12:38 +01001398 }
1399
Soonil Nagarkarfc9c7f82019-07-16 12:07:57 -07001400 if (mStarted) {
Wyatt Rileyc7067412018-02-07 15:50:35 -08001401 // For devices that use framework scheduling, a timer may be set to ensure we don't
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001402 // spend too much power searching for a location, when the requested update rate is
1403 // slow.
Wyatt Rileyc7067412018-02-07 15:50:35 -08001404 // As we just recievied a location, we'll cancel that timer.
Mike Lockwood04598b62010-04-14 17:17:24 -04001405 if (!hasCapability(GPS_CAPABILITY_SCHEDULING) && mFixInterval < NO_FIX_TIMEOUT) {
Mike Lockwoodb7be5442010-02-24 14:34:50 -05001406 mAlarmManager.cancel(mTimeoutIntent);
1407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 }
Mike Lockwood29c84342009-05-06 14:01:15 -04001409
gomo48f1a642017-11-10 20:35:46 -08001410 if (!hasCapability(GPS_CAPABILITY_SCHEDULING) && mStarted &&
1411 mFixInterval > GPS_POLLING_THRESHOLD_INTERVAL) {
Mike Lockwoodd53ba012010-04-15 20:41:26 -04001412 if (DEBUG) Log.d(TAG, "got fix, hibernating");
Mike Lockwood0632ca72009-05-14 15:51:03 -04001413 hibernate();
Mike Lockwood29c84342009-05-06 14:01:15 -04001414 }
gomo48f1a642017-11-10 20:35:46 -08001415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001417 @NativeEntryPoint
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 private void reportStatus(int status) {
Mike Lockwoodb8d90332010-10-18 17:59:48 -04001419 if (DEBUG) Log.v(TAG, "reportStatus status: " + status);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420
destradaaea8a8a62014-06-23 18:19:03 -07001421 boolean wasNavigating = mNavigating;
1422 switch (status) {
1423 case GPS_STATUS_SESSION_BEGIN:
1424 mNavigating = true;
destradaaea8a8a62014-06-23 18:19:03 -07001425 break;
1426 case GPS_STATUS_SESSION_END:
1427 mNavigating = false;
1428 break;
1429 case GPS_STATUS_ENGINE_ON:
destradaaea8a8a62014-06-23 18:19:03 -07001430 break;
1431 case GPS_STATUS_ENGINE_OFF:
destradaaea8a8a62014-06-23 18:19:03 -07001432 mNavigating = false;
1433 break;
1434 }
Mike Lockwooddbd6fd82009-12-07 18:43:36 -05001435
destradaaea8a8a62014-06-23 18:19:03 -07001436 if (wasNavigating != mNavigating) {
Anil Admal75b9fd62018-11-28 11:22:50 -08001437 mGnssStatusListenerHelper.onStatusChanged(mNavigating);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
1439 }
1440
Wyatt Riley26465d22018-02-12 13:44:24 -08001441 // Helper class to carry data to handler for reportSvStatus
1442 private static class SvStatusInfo {
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001443 private int mSvCount;
1444 private int[] mSvidWithFlags;
1445 private float[] mCn0s;
1446 private float[] mSvElevations;
1447 private float[] mSvAzimuths;
1448 private float[] mSvCarrierFreqs;
Wyatt Riley26465d22018-02-12 13:44:24 -08001449 }
1450
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001451 @NativeEntryPoint
Wyatt Riley26465d22018-02-12 13:44:24 -08001452 private void reportSvStatus(int svCount, int[] svidWithFlags, float[] cn0s,
1453 float[] svElevations, float[] svAzimuths, float[] svCarrierFreqs) {
1454 SvStatusInfo svStatusInfo = new SvStatusInfo();
1455 svStatusInfo.mSvCount = svCount;
1456 svStatusInfo.mSvidWithFlags = svidWithFlags;
1457 svStatusInfo.mCn0s = cn0s;
1458 svStatusInfo.mSvElevations = svElevations;
1459 svStatusInfo.mSvAzimuths = svAzimuths;
1460 svStatusInfo.mSvCarrierFreqs = svCarrierFreqs;
1461
1462 sendMessage(REPORT_SV_STATUS, 0, svStatusInfo);
1463 }
1464
1465 private void handleReportSvStatus(SvStatusInfo info) {
Anil Admal75b9fd62018-11-28 11:22:50 -08001466 mGnssStatusListenerHelper.onSvStatusChanged(
Wyatt Riley26465d22018-02-12 13:44:24 -08001467 info.mSvCount,
1468 info.mSvidWithFlags,
1469 info.mCn0s,
1470 info.mSvElevations,
1471 info.mSvAzimuths,
1472 info.mSvCarrierFreqs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473
Siddharth Ray168f12a2017-07-10 11:55:10 -07001474 // Log CN0 as part of GNSS metrics
Blake Kragtenbb613602019-08-28 16:21:35 -07001475 mGnssMetrics.logCn0(info.mCn0s, info.mSvCount, info.mSvCarrierFreqs);
Siddharth Ray168f12a2017-07-10 11:55:10 -07001476
Mike Lockwood29c84342009-05-06 14:01:15 -04001477 if (VERBOSE) {
Wyatt Riley26465d22018-02-12 13:44:24 -08001478 Log.v(TAG, "SV count: " + info.mSvCount);
Lifu Tang30f95a72016-01-07 23:20:38 -08001479 }
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001480 // Calculate number of satellites used in fix.
Soonil Nagarkar0d1890b2019-11-12 12:13:14 -08001481 GnssStatus gnssStatus = GnssStatus.wrap(
1482 info.mSvCount,
1483 info.mSvidWithFlags,
1484 info.mCn0s,
1485 info.mSvElevations,
1486 info.mSvAzimuths,
1487 info.mSvCarrierFreqs);
Lifu Tang30f95a72016-01-07 23:20:38 -08001488 int usedInFixCount = 0;
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001489 int maxCn0 = 0;
1490 int meanCn0 = 0;
Soonil Nagarkar0d1890b2019-11-12 12:13:14 -08001491 for (int i = 0; i < gnssStatus.getSatelliteCount(); i++) {
1492 if (gnssStatus.usedInFix(i)) {
Lifu Tang30f95a72016-01-07 23:20:38 -08001493 ++usedInFixCount;
Soonil Nagarkar0d1890b2019-11-12 12:13:14 -08001494 if (gnssStatus.getCn0DbHz(i) > maxCn0) {
1495 maxCn0 = (int) gnssStatus.getCn0DbHz(i);
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001496 }
Soonil Nagarkar0d1890b2019-11-12 12:13:14 -08001497 meanCn0 += gnssStatus.getCn0DbHz(i);
1498 mGnssMetrics.logConstellationType(gnssStatus.getConstellationType(i));
Lifu Tang30f95a72016-01-07 23:20:38 -08001499 }
1500 if (VERBOSE) {
Soonil Nagarkar0d1890b2019-11-12 12:13:14 -08001501 Log.v(TAG, "svid: " + gnssStatus.getSvid(i)
1502 + " cn0: " + gnssStatus.getCn0DbHz(i)
1503 + " elev: " + gnssStatus.getElevationDegrees(i)
1504 + " azimuth: " + gnssStatus.getAzimuthDegrees(i)
1505 + " carrier frequency: " + gnssStatus.getCn0DbHz(i)
1506 + (gnssStatus.hasEphemerisData(i) ? " E" : " ")
1507 + (gnssStatus.hasAlmanacData(i) ? " A" : " ")
1508 + (gnssStatus.usedInFix(i) ? "U" : "")
1509 + (gnssStatus.hasCarrierFrequencyHz(i) ? "F" : ""));
Yu-Han Yang284234e2019-03-28 19:35:57 -07001510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001512 if (usedInFixCount > 0) {
1513 meanCn0 /= usedInFixCount;
1514 }
1515 // return number of sats used in fix instead of total reported
Wyatt Rileyc7067412018-02-07 15:50:35 -08001516 mLocationExtras.set(usedInFixCount, meanCn0, maxCn0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517
Soonil Nagarkar0d1890b2019-11-12 12:13:14 -08001518 mGnssMetrics.logSvStatus(gnssStatus);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 }
Mike Lockwood58bda982009-04-14 16:25:07 -04001520
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001521 @NativeEntryPoint
Anil Admalc70344b2018-11-16 14:22:38 -08001522 private void reportAGpsStatus(int agpsType, int agpsStatus, byte[] suplIpAddr) {
1523 mNetworkConnectivityHandler.onReportAGpsStatus(agpsType, agpsStatus, suplIpAddr);
destradaae21252a2015-09-08 12:32:59 -07001524 }
1525
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001526 @NativeEntryPoint
Mike Lockwoodf602d362010-06-20 14:28:16 -07001527 private void reportNmea(long timestamp) {
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001528 if (!mItarSpeedLimitExceeded) {
1529 int length = native_read_nmea(mNmeaBuffer, mNmeaBuffer.length);
1530 String nmea = new String(mNmeaBuffer, 0 /* offset */, length);
Anil Admal75b9fd62018-11-28 11:22:50 -08001531 mGnssStatusListenerHelper.onNmeaReceived(timestamp, nmea);
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001532 }
destradaaea8a8a62014-06-23 18:19:03 -07001533 }
Mike Lockwoodb16e7802009-08-06 09:26:02 -04001534
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001535 @NativeEntryPoint
Lifu Tang818aa2c2016-02-01 01:52:00 -08001536 private void reportMeasurementData(GnssMeasurementsEvent event) {
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001537 if (!mItarSpeedLimitExceeded) {
Wyatt Rileyaa420d52017-07-03 15:14:42 -07001538 // send to handler to allow native to return quickly
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001539 mHandler.post(() -> mGnssMeasurementsProvider.onMeasurementsAvailable(event));
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001540 }
Mike Lockwoodb16e7802009-08-06 09:26:02 -04001541 }
1542
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001543 @NativeEntryPoint
Lifu Tange8abe8e2016-04-01 10:32:05 -07001544 private void reportNavigationMessage(GnssNavigationMessage event) {
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001545 if (!mItarSpeedLimitExceeded) {
Wyatt Rileyaa420d52017-07-03 15:14:42 -07001546 // send to handler to allow native to return quickly
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001547 mHandler.post(() -> mGnssNavigationMessageProvider.onNavigationMessageAvailable(event));
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001548 }
destradaa4b3e3932014-07-21 18:01:47 -07001549 }
1550
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001551 @NativeEntryPoint
Anil Admal62c42dc2019-04-03 15:39:22 -07001552 private void setTopHalCapabilities(int topHalCapabilities) {
Anil Admalefd9dc62019-03-12 17:39:20 -07001553 mHandler.post(() -> {
Anil Admal312fddb2019-03-25 12:15:43 -07001554 mTopHalCapabilities = topHalCapabilities;
Mike Lockwood9b9fb5c2011-06-29 15:09:40 -04001555
Anil Admalefd9dc62019-03-12 17:39:20 -07001556 if (hasCapability(GPS_CAPABILITY_ON_DEMAND_TIME)) {
1557 mNtpTimeHelper.enablePeriodicTimeInjection();
1558 requestUtcTime();
1559 }
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001560
Anil Admal62c42dc2019-04-03 15:39:22 -07001561 mGnssMeasurementsProvider.onCapabilitiesUpdated(
1562 hasCapability(GPS_CAPABILITY_MEASUREMENTS));
1563 mGnssNavigationMessageProvider.onCapabilitiesUpdated(
1564 hasCapability(GPS_CAPABILITY_NAV_MESSAGES));
Anil Admalefd9dc62019-03-12 17:39:20 -07001565 restartRequests();
Anil Admal312fddb2019-03-25 12:15:43 -07001566
Anil Admal62c42dc2019-04-03 15:39:22 -07001567 mGnssCapabilitiesProvider.setTopHalCapabilities(mTopHalCapabilities);
Anil Admalefd9dc62019-03-12 17:39:20 -07001568 });
1569 }
1570
1571 @NativeEntryPoint
Anil Admal312fddb2019-03-25 12:15:43 -07001572 private void setSubHalMeasurementCorrectionsCapabilities(int subHalCapabilities) {
1573 mHandler.post(() -> {
1574 if (!mGnssMeasurementCorrectionsProvider.onCapabilitiesUpdated(subHalCapabilities)) {
1575 return;
1576 }
1577
1578 mGnssCapabilitiesProvider.setSubHalMeasurementCorrectionsCapabilities(
1579 subHalCapabilities);
1580 });
Yu-Han Yang52057622018-04-25 00:51:22 -07001581 }
1582
1583 private void restartRequests() {
1584 Log.i(TAG, "restartRequests");
1585
1586 restartLocationRequest();
1587 mGnssMeasurementsProvider.resumeIfStarted();
1588 mGnssNavigationMessageProvider.resumeIfStarted();
1589 mGnssBatchingProvider.resumeIfStarted();
1590 mGnssGeofenceProvider.resumeIfStarted();
1591 }
1592
1593 private void restartLocationRequest() {
1594 if (DEBUG) Log.d(TAG, "restartLocationRequest");
WyattRileyba6072f2019-04-18 07:37:52 -07001595 setStarted(false);
Yu-Han Yang52057622018-04-25 00:51:22 -07001596 updateRequirements();
1597 }
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001598
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001599 @NativeEntryPoint
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001600 private void setGnssYearOfHardware(final int yearOfHardware) {
1601 // mHardwareYear is simply set here, to be read elsewhere, and is volatile for safe sync
1602 if (DEBUG) Log.d(TAG, "setGnssYearOfHardware called with " + yearOfHardware);
1603 mHardwareYear = yearOfHardware;
Mike Lockwood04598b62010-04-14 17:17:24 -04001604 }
1605
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001606 @NativeEntryPoint
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001607 private void setGnssHardwareModelName(final String modelName) {
1608 // mHardwareModelName is simply set here, to be read elsewhere, and volatile for safe sync
1609 if (DEBUG) Log.d(TAG, "setGnssModelName called with " + modelName);
1610 mHardwareModelName = modelName;
Lifu Tang82f893d2016-01-21 18:15:33 -08001611 }
1612
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001613 @NativeEntryPoint
Yu-Han Yang52057622018-04-25 00:51:22 -07001614 private void reportGnssServiceDied() {
1615 if (DEBUG) Log.d(TAG, "reportGnssServiceDied");
1616 mHandler.post(() -> {
Anil Admal0c2b21bd2019-05-03 18:29:02 -07001617 setupNativeGnssService(/* reinitializeGnssServiceHandle = */ true);
Anil Admal204406f2019-07-23 12:00:23 -07001618 // resend configuration into the restarted HAL service.
1619 reloadGpsProperties();
Yu-Han Yang76f99952019-05-04 17:45:44 -07001620 if (isGpsEnabled()) {
1621 setGpsEnabled(false);
Soonil Nagarkar35c3b912019-01-31 10:31:24 -08001622 updateEnabled();
Yu-Han Yang52057622018-04-25 00:51:22 -07001623 }
1624 });
1625 }
1626
Lifu Tang9363b942016-02-16 18:07:00 -08001627 public interface GnssSystemInfoProvider {
Lifu Tang82f893d2016-01-21 18:15:33 -08001628 /**
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001629 * Returns the year of underlying GPS hardware.
Lifu Tang82f893d2016-01-21 18:15:33 -08001630 */
Lifu Tang9363b942016-02-16 18:07:00 -08001631 int getGnssYearOfHardware();
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001632
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001633 /**
1634 * Returns the model name of underlying GPS hardware.
1635 */
1636 String getGnssHardwareModelName();
Lifu Tang82f893d2016-01-21 18:15:33 -08001637 }
1638
1639 /**
1640 * @hide
1641 */
Lifu Tang9363b942016-02-16 18:07:00 -08001642 public GnssSystemInfoProvider getGnssSystemInfoProvider() {
1643 return new GnssSystemInfoProvider() {
Lifu Tang82f893d2016-01-21 18:15:33 -08001644 @Override
Lifu Tang9363b942016-02-16 18:07:00 -08001645 public int getGnssYearOfHardware() {
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001646 return mHardwareYear;
1647 }
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001648
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001649 @Override
1650 public String getGnssHardwareModelName() {
1651 return mHardwareModelName;
Lifu Tang82f893d2016-01-21 18:15:33 -08001652 }
1653 };
1654 }
1655
Wyatt Rileycf879db2017-01-12 13:57:38 -08001656 /**
1657 * @hide
1658 */
1659 public GnssBatchingProvider getGnssBatchingProvider() {
Yu-Han Yang3557cc72018-03-21 12:48:36 -07001660 return mGnssBatchingProvider;
Wyatt Rileycf879db2017-01-12 13:57:38 -08001661 }
1662
Siddharth Raybb608c82017-03-16 11:33:34 -07001663 public interface GnssMetricsProvider {
1664 /**
1665 * Returns GNSS metrics as proto string
1666 */
1667 String getGnssMetricsAsProtoString();
1668 }
1669
1670 /**
1671 * @hide
1672 */
1673 public GnssMetricsProvider getGnssMetricsProvider() {
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001674 return () -> mGnssMetrics.dumpGnssMetricsAsProtoString();
Siddharth Raybb608c82017-03-16 11:33:34 -07001675 }
1676
Anil Admal312fddb2019-03-25 12:15:43 -07001677 /**
1678 * @hide
1679 */
1680 public GnssCapabilitiesProvider getGnssCapabilitiesProvider() {
1681 return mGnssCapabilitiesProvider;
1682 }
1683
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001684 @NativeEntryPoint
Wyatt Rileycf879db2017-01-12 13:57:38 -08001685 private void reportLocationBatch(Location[] locationArray) {
1686 List<Location> locations = new ArrayList<>(Arrays.asList(locationArray));
gomo48f1a642017-11-10 20:35:46 -08001687 if (DEBUG) {
1688 Log.d(TAG, "Location batch of size " + locationArray.length + " reported");
1689 }
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001690 reportLocation(locations);
Wyatt Rileycf879db2017-01-12 13:57:38 -08001691 }
1692
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001693 @NativeEntryPoint
Kevin Tang8c6ac672019-03-22 12:31:01 -07001694 private void psdsDownloadRequest() {
1695 if (DEBUG) Log.d(TAG, "psdsDownloadRequest");
1696 sendMessage(DOWNLOAD_PSDS_DATA, 0, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 }
1698
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001699 /**
destradaa0682809a2013-08-12 18:50:30 -07001700 * Converts the GPS HAL status to the internal Geofence Hardware status.
1701 */
Yu-Han Yang6dc9f052018-12-04 17:11:24 -08001702 private static int getGeofenceStatus(int status) {
gomo48f1a642017-11-10 20:35:46 -08001703 switch (status) {
destradaa0682809a2013-08-12 18:50:30 -07001704 case GPS_GEOFENCE_OPERATION_SUCCESS:
1705 return GeofenceHardware.GEOFENCE_SUCCESS;
1706 case GPS_GEOFENCE_ERROR_GENERIC:
1707 return GeofenceHardware.GEOFENCE_FAILURE;
1708 case GPS_GEOFENCE_ERROR_ID_EXISTS:
1709 return GeofenceHardware.GEOFENCE_ERROR_ID_EXISTS;
1710 case GPS_GEOFENCE_ERROR_INVALID_TRANSITION:
1711 return GeofenceHardware.GEOFENCE_ERROR_INVALID_TRANSITION;
1712 case GPS_GEOFENCE_ERROR_TOO_MANY_GEOFENCES:
1713 return GeofenceHardware.GEOFENCE_ERROR_TOO_MANY_GEOFENCES;
1714 case GPS_GEOFENCE_ERROR_ID_UNKNOWN:
1715 return GeofenceHardware.GEOFENCE_ERROR_ID_UNKNOWN;
1716 default:
1717 return -1;
1718 }
1719 }
1720
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001721 @NativeEntryPoint
Wyatt Riley5d229832017-02-10 17:06:00 -08001722 private void reportGeofenceTransition(int geofenceId, Location location, int transition,
gomo48f1a642017-11-10 20:35:46 -08001723 long transitionTimestamp) {
Yu-Han Yang6dc9f052018-12-04 17:11:24 -08001724 mHandler.post(() -> {
1725 if (mGeofenceHardwareImpl == null) {
1726 mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
1727 }
Wyatt Riley5d229832017-02-10 17:06:00 -08001728
Yu-Han Yang6dc9f052018-12-04 17:11:24 -08001729 mGeofenceHardwareImpl.reportGeofenceTransition(
1730 geofenceId,
1731 location,
1732 transition,
1733 transitionTimestamp,
1734 GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE,
1735 FusedBatchOptions.SourceTechnologies.GNSS);
1736 });
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001737 }
1738
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001739 @NativeEntryPoint
Wyatt Riley5d229832017-02-10 17:06:00 -08001740 private void reportGeofenceStatus(int status, Location location) {
Yu-Han Yang6dc9f052018-12-04 17:11:24 -08001741 mHandler.post(() -> {
1742 if (mGeofenceHardwareImpl == null) {
1743 mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
1744 }
1745 int monitorStatus = GeofenceHardware.MONITOR_CURRENTLY_UNAVAILABLE;
1746 if (status == GPS_GEOFENCE_AVAILABLE) {
1747 monitorStatus = GeofenceHardware.MONITOR_CURRENTLY_AVAILABLE;
1748 }
1749 mGeofenceHardwareImpl.reportGeofenceMonitorStatus(
1750 GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE,
1751 monitorStatus,
1752 location,
1753 FusedBatchOptions.SourceTechnologies.GNSS);
1754 });
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001755 }
1756
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001757 @NativeEntryPoint
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001758 private void reportGeofenceAddStatus(int geofenceId, int status) {
Yu-Han Yang6dc9f052018-12-04 17:11:24 -08001759 mHandler.post(() -> {
1760 if (mGeofenceHardwareImpl == null) {
1761 mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
1762 }
1763 mGeofenceHardwareImpl.reportGeofenceAddStatus(geofenceId, getGeofenceStatus(status));
1764 });
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001765 }
1766
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001767 @NativeEntryPoint
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001768 private void reportGeofenceRemoveStatus(int geofenceId, int status) {
Yu-Han Yang6dc9f052018-12-04 17:11:24 -08001769 mHandler.post(() -> {
1770 if (mGeofenceHardwareImpl == null) {
1771 mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
1772 }
1773 mGeofenceHardwareImpl.reportGeofenceRemoveStatus(geofenceId, getGeofenceStatus(status));
1774 });
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001775 }
1776
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001777 @NativeEntryPoint
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001778 private void reportGeofencePauseStatus(int geofenceId, int status) {
Yu-Han Yang6dc9f052018-12-04 17:11:24 -08001779 mHandler.post(() -> {
1780 if (mGeofenceHardwareImpl == null) {
1781 mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
1782 }
1783 mGeofenceHardwareImpl.reportGeofencePauseStatus(geofenceId, getGeofenceStatus(status));
1784 });
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001785 }
1786
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001787 @NativeEntryPoint
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001788 private void reportGeofenceResumeStatus(int geofenceId, int status) {
Yu-Han Yang6dc9f052018-12-04 17:11:24 -08001789 mHandler.post(() -> {
1790 if (mGeofenceHardwareImpl == null) {
1791 mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
1792 }
1793 mGeofenceHardwareImpl.reportGeofenceResumeStatus(geofenceId, getGeofenceStatus(status));
1794 });
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001795 }
1796
Danke Xie22d1f9f2009-08-18 18:28:45 -04001797 //=============================================================
1798 // NI Client support
Miguel Torroja1e84da82010-07-27 07:02:24 +02001799 //=============================================================
Danke Xie22d1f9f2009-08-18 18:28:45 -04001800 private final INetInitiatedListener mNetInitiatedListener = new INetInitiatedListener.Stub() {
destradaaef752b62015-04-17 13:10:47 -07001801 // Sends a response for an NI request to HAL.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001802 @Override
gomo48f1a642017-11-10 20:35:46 -08001803 public boolean sendNiResponse(int notificationId, int userResponse) {
Miguel Torroja1e84da82010-07-27 07:02:24 +02001804 // TODO Add Permission check
Danke Xie22d1f9f2009-08-18 18:28:45 -04001805
gomo48f1a642017-11-10 20:35:46 -08001806 if (DEBUG) {
1807 Log.d(TAG, "sendNiResponse, notifId: " + notificationId +
1808 ", response: " + userResponse);
1809 }
Miguel Torroja1e84da82010-07-27 07:02:24 +02001810 native_send_ni_response(notificationId, userResponse);
Yu-Han Yang8a1b51d2018-12-26 22:18:31 -08001811
1812 StatsLog.write(StatsLog.GNSS_NI_EVENT_REPORTED,
1813 StatsLog.GNSS_NI_EVENT_REPORTED__EVENT_TYPE__NI_RESPONSE,
1814 notificationId,
1815 /* niType= */ 0,
1816 /* needNotify= */ false,
1817 /* needVerify= */ false,
1818 /* privacyOverride= */ false,
1819 /* timeout= */ 0,
1820 /* defaultResponse= */ 0,
1821 /* requestorId= */ null,
1822 /* text= */ null,
1823 /* requestorIdEncoding= */ 0,
1824 /* textEncoding= */ 0,
1825 mSuplEsEnabled,
Yu-Han Yang76f99952019-05-04 17:45:44 -07001826 isGpsEnabled(),
Yu-Han Yang8a1b51d2018-12-26 22:18:31 -08001827 userResponse);
1828
Miguel Torroja1e84da82010-07-27 07:02:24 +02001829 return true;
1830 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04001831 };
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001832
Danke Xie22d1f9f2009-08-18 18:28:45 -04001833 public INetInitiatedListener getNetInitiatedListener() {
1834 return mNetInitiatedListener;
1835 }
1836
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001837 /** Reports a NI notification. */
1838 @NativeEntryPoint
Miguel Torroja1e84da82010-07-27 07:02:24 +02001839 public void reportNiNotification(
1840 int notificationId,
1841 int niType,
1842 int notifyFlags,
1843 int timeout,
1844 int defaultResponse,
1845 String requestorId,
1846 String text,
1847 int requestorIdEncoding,
Hridya Valsaraju2ea29602016-09-13 08:38:09 -07001848 int textEncoding
gomo48f1a642017-11-10 20:35:46 -08001849 ) {
Miguel Torroja1e84da82010-07-27 07:02:24 +02001850 Log.i(TAG, "reportNiNotification: entered");
1851 Log.i(TAG, "notificationId: " + notificationId +
1852 ", niType: " + niType +
1853 ", notifyFlags: " + notifyFlags +
1854 ", timeout: " + timeout +
1855 ", defaultResponse: " + defaultResponse);
1856
1857 Log.i(TAG, "requestorId: " + requestorId +
1858 ", text: " + text +
1859 ", requestorIdEncoding: " + requestorIdEncoding +
1860 ", textEncoding: " + textEncoding);
1861
1862 GpsNiNotification notification = new GpsNiNotification();
1863
1864 notification.notificationId = notificationId;
1865 notification.niType = niType;
1866 notification.needNotify = (notifyFlags & GpsNetInitiatedHandler.GPS_NI_NEED_NOTIFY) != 0;
1867 notification.needVerify = (notifyFlags & GpsNetInitiatedHandler.GPS_NI_NEED_VERIFY) != 0;
gomo48f1a642017-11-10 20:35:46 -08001868 notification.privacyOverride =
1869 (notifyFlags & GpsNetInitiatedHandler.GPS_NI_PRIVACY_OVERRIDE) != 0;
Miguel Torroja1e84da82010-07-27 07:02:24 +02001870 notification.timeout = timeout;
1871 notification.defaultResponse = defaultResponse;
1872 notification.requestorId = requestorId;
1873 notification.text = text;
1874 notification.requestorIdEncoding = requestorIdEncoding;
1875 notification.textEncoding = textEncoding;
1876
Miguel Torroja1e84da82010-07-27 07:02:24 +02001877 mNIHandler.handleNiNotification(notification);
Yu-Han Yang8a1b51d2018-12-26 22:18:31 -08001878 StatsLog.write(StatsLog.GNSS_NI_EVENT_REPORTED,
1879 StatsLog.GNSS_NI_EVENT_REPORTED__EVENT_TYPE__NI_REQUEST,
1880 notification.notificationId,
1881 notification.niType,
1882 notification.needNotify,
1883 notification.needVerify,
1884 notification.privacyOverride,
1885 notification.timeout,
1886 notification.defaultResponse,
1887 notification.requestorId,
1888 notification.text,
1889 notification.requestorIdEncoding,
1890 notification.textEncoding,
1891 mSuplEsEnabled,
Yu-Han Yang76f99952019-05-04 17:45:44 -07001892 isGpsEnabled(),
Yu-Han Yang8a1b51d2018-12-26 22:18:31 -08001893 /* userResponse= */ 0);
Miguel Torroja1e84da82010-07-27 07:02:24 +02001894 }
1895
1896 /**
Miguel Torroja1e84da82010-07-27 07:02:24 +02001897 * We should be careful about receiving null string from the TelephonyManager,
1898 * because sending null String to JNI function would cause a crash.
1899 */
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001900 @NativeEntryPoint
Miguel Torroja1e84da82010-07-27 07:02:24 +02001901 private void requestSetID(int flags) {
1902 TelephonyManager phone = (TelephonyManager)
1903 mContext.getSystemService(Context.TELEPHONY_SERVICE);
destradaaef752b62015-04-17 13:10:47 -07001904 int type = AGPS_SETID_TYPE_NONE;
Anil Admale1539e82019-05-09 15:05:04 -07001905 String setId = null;
Miguel Torroja1e84da82010-07-27 07:02:24 +02001906
Anil Admale1539e82019-05-09 15:05:04 -07001907 int ddSubId = SubscriptionManager.getDefaultDataSubscriptionId();
Miguel Torroja1e84da82010-07-27 07:02:24 +02001908 if ((flags & AGPS_RIL_REQUEST_SETID_IMSI) == AGPS_RIL_REQUEST_SETID_IMSI) {
Anil Admale1539e82019-05-09 15:05:04 -07001909 if (SubscriptionManager.isValidSubscriptionId(ddSubId)) {
1910 setId = phone.getSubscriberId(ddSubId);
1911 }
1912 if (setId == null) {
1913 setId = phone.getSubscriberId();
1914 }
1915 if (setId != null) {
Miguel Torroja1e84da82010-07-27 07:02:24 +02001916 // This means the framework has the SIM card.
Miguel Torroja1e84da82010-07-27 07:02:24 +02001917 type = AGPS_SETID_TYPE_IMSI;
1918 }
gomo48f1a642017-11-10 20:35:46 -08001919 } else if ((flags & AGPS_RIL_REQUEST_SETID_MSISDN) == AGPS_RIL_REQUEST_SETID_MSISDN) {
Anil Admale1539e82019-05-09 15:05:04 -07001920 if (SubscriptionManager.isValidSubscriptionId(ddSubId)) {
1921 setId = phone.getLine1Number(ddSubId);
1922 }
1923 if (setId == null) {
1924 setId = phone.getLine1Number();
1925 }
1926 if (setId != null) {
Miguel Torroja1e84da82010-07-27 07:02:24 +02001927 // This means the framework has the SIM card.
Miguel Torroja1e84da82010-07-27 07:02:24 +02001928 type = AGPS_SETID_TYPE_MSISDN;
1929 }
1930 }
Anil Admale1539e82019-05-09 15:05:04 -07001931
1932 native_agps_set_id(type, (setId == null) ? "" : setId);
Miguel Torroja1e84da82010-07-27 07:02:24 +02001933 }
1934
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001935 @NativeEntryPoint
Yu-Han Yang53f4d6d2019-02-13 21:47:41 -08001936 private void requestLocation(boolean independentFromGnss, boolean isUserEmergency) {
Yu-Han Yange7baef32018-02-09 13:58:17 -08001937 if (DEBUG) {
Yu-Han Yang53f4d6d2019-02-13 21:47:41 -08001938 Log.d(TAG, "requestLocation. independentFromGnss: " + independentFromGnss
1939 + ", isUserEmergency: "
1940 + isUserEmergency);
Yu-Han Yange7baef32018-02-09 13:58:17 -08001941 }
Yu-Han Yang53f4d6d2019-02-13 21:47:41 -08001942 sendMessage(REQUEST_LOCATION, independentFromGnss ? 1 : 0, isUserEmergency);
Yu-Han Yange7baef32018-02-09 13:58:17 -08001943 }
1944
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001945 @NativeEntryPoint
Mike Lockwood9b9fb5c2011-06-29 15:09:40 -04001946 private void requestUtcTime() {
destradaae21252a2015-09-08 12:32:59 -07001947 if (DEBUG) Log.d(TAG, "utcTimeRequest");
Mike Lockwood9b9fb5c2011-06-29 15:09:40 -04001948 sendMessage(INJECT_NTP_TIME, 0, null);
1949 }
1950
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001951 @NativeEntryPoint
Hridya Valsaraju2ea29602016-09-13 08:38:09 -07001952 private void requestRefLocation() {
Miguel Torroja1e84da82010-07-27 07:02:24 +02001953 TelephonyManager phone = (TelephonyManager)
1954 mContext.getSystemService(Context.TELEPHONY_SERVICE);
Victoria Leased50d0c32012-10-29 13:16:17 -07001955 final int phoneType = phone.getPhoneType();
1956 if (phoneType == TelephonyManager.PHONE_TYPE_GSM) {
Miguel Torroja1e84da82010-07-27 07:02:24 +02001957 GsmCellLocation gsm_cell = (GsmCellLocation) phone.getCellLocation();
Victoria Leased50d0c32012-10-29 13:16:17 -07001958 if ((gsm_cell != null) && (phone.getNetworkOperator() != null)
1959 && (phone.getNetworkOperator().length() > 3)) {
Miguel Torroja1e84da82010-07-27 07:02:24 +02001960 int type;
gomo48f1a642017-11-10 20:35:46 -08001961 int mcc = Integer.parseInt(phone.getNetworkOperator().substring(0, 3));
Miguel Torroja1e84da82010-07-27 07:02:24 +02001962 int mnc = Integer.parseInt(phone.getNetworkOperator().substring(3));
Mike Lockwoodedc0f3872010-10-22 09:16:17 -04001963 int networkType = phone.getNetworkType();
1964 if (networkType == TelephonyManager.NETWORK_TYPE_UMTS
gomo48f1a642017-11-10 20:35:46 -08001965 || networkType == TelephonyManager.NETWORK_TYPE_HSDPA
1966 || networkType == TelephonyManager.NETWORK_TYPE_HSUPA
1967 || networkType == TelephonyManager.NETWORK_TYPE_HSPA
1968 || networkType == TelephonyManager.NETWORK_TYPE_HSPAP) {
Miguel Torroja1e84da82010-07-27 07:02:24 +02001969 type = AGPS_REF_LOCATION_TYPE_UMTS_CELLID;
Mike Lockwoodedc0f3872010-10-22 09:16:17 -04001970 } else {
Miguel Torroja1e84da82010-07-27 07:02:24 +02001971 type = AGPS_REF_LOCATION_TYPE_GSM_CELLID;
Mike Lockwoodedc0f3872010-10-22 09:16:17 -04001972 }
Miguel Torroja1e84da82010-07-27 07:02:24 +02001973 native_agps_set_ref_location_cellid(type, mcc, mnc,
1974 gsm_cell.getLac(), gsm_cell.getCid());
Mike Lockwoodedc0f3872010-10-22 09:16:17 -04001975 } else {
gomo48f1a642017-11-10 20:35:46 -08001976 Log.e(TAG, "Error getting cell location info.");
Mike Lockwoodedc0f3872010-10-22 09:16:17 -04001977 }
Victoria Leased50d0c32012-10-29 13:16:17 -07001978 } else if (phoneType == TelephonyManager.PHONE_TYPE_CDMA) {
1979 Log.e(TAG, "CDMA not supported.");
Mike Lockwoodedc0f3872010-10-22 09:16:17 -04001980 }
Miguel Torroja1e84da82010-07-27 07:02:24 +02001981 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04001982
Anil Admal94ec76a2019-01-15 09:42:01 -08001983 // Implements method nfwNotifyCb() in IGnssVisibilityControlCallback.hal.
1984 @NativeEntryPoint
1985 private void reportNfwNotification(String proxyAppPackageName, byte protocolStack,
1986 String otherProtocolStackName, byte requestor, String requestorId, byte responseType,
1987 boolean inEmergencyMode, boolean isCachedLocation) {
1988 if (mGnssVisibilityControl == null) {
1989 Log.e(TAG, "reportNfwNotification: mGnssVisibilityControl is not initialized.");
1990 return;
1991 }
1992
1993 mGnssVisibilityControl.reportNfwNotification(proxyAppPackageName, protocolStack,
1994 otherProtocolStackName, requestor, requestorId, responseType, inEmergencyMode,
1995 isCachedLocation);
1996 }
1997
1998 // Implements method isInEmergencySession() in IGnssVisibilityControlCallback.hal.
1999 @NativeEntryPoint
2000 boolean isInEmergencySession() {
2001 return mNIHandler.getInEmergency();
2002 }
2003
Mike Lockwood98e48692010-04-07 16:32:51 -04002004 private void sendMessage(int message, int arg, Object obj) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002005 // hold a wake lock until this message is delivered
Jeff Brown028872f2012-08-25 13:07:01 -07002006 // note that this assumes the message will not be removed from the queue before
2007 // it is handled (otherwise the wake lock would be leaked).
Yu-Han Yang499a6ba2019-11-14 14:19:13 -08002008 mWakeLock.acquire(WAKELOCK_TIMEOUT_MILLIS);
Anil Admal4f97c942018-11-12 10:52:46 -08002009 if (DEBUG) {
2010 Log.d(TAG, "WakeLock acquired by sendMessage(" + messageIdAsString(message) + ", " + arg
Wyatt Rileycf879db2017-01-12 13:57:38 -08002011 + ", " + obj + ")");
2012 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002013 mHandler.obtainMessage(message, arg, 1, obj).sendToTarget();
Mike Lockwood98e48692010-04-07 16:32:51 -04002014 }
2015
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002016 private final class ProviderHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08002017 public ProviderHandler(Looper looper) {
2018 super(looper, null, true /*async*/);
Jeff Brown028872f2012-08-25 13:07:01 -07002019 }
2020
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002021 @Override
Mike Lockwood4a7b65e2010-10-25 16:35:55 -04002022 public void handleMessage(Message msg) {
Mike Lockwood98e48692010-04-07 16:32:51 -04002023 int message = msg.what;
2024 switch (message) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002025 case SET_REQUEST:
2026 GpsRequest gpsRequest = (GpsRequest) msg.obj;
2027 handleSetRequest(gpsRequest.request, gpsRequest.source);
Mike Lockwood03ca2162010-04-01 08:10:09 -07002028 break;
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002029 case INJECT_NTP_TIME:
Yu-Han Yanga1862b52018-02-20 17:05:59 -08002030 mNtpTimeHelper.retrieveAndInjectNtpTime();
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002031 break;
Yu-Han Yange7baef32018-02-09 13:58:17 -08002032 case REQUEST_LOCATION:
Yu-Han Yang53f4d6d2019-02-13 21:47:41 -08002033 handleRequestLocation(msg.arg1 == 1, (boolean) msg.obj);
Yu-Han Yange7baef32018-02-09 13:58:17 -08002034 break;
Kevin Tang8c6ac672019-03-22 12:31:01 -07002035 case DOWNLOAD_PSDS_DATA:
2036 handleDownloadPsdsData();
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002037 break;
Kevin Tang8c6ac672019-03-22 12:31:01 -07002038 case DOWNLOAD_PSDS_DATA_FINISHED:
2039 mDownloadPsdsDataPending = STATE_IDLE;
Kevin Tang40e1baf2012-01-10 14:32:44 -08002040 break;
destradaafb23c672015-04-16 14:01:27 -07002041 case INITIALIZE_HANDLER:
destradaae21252a2015-09-08 12:32:59 -07002042 handleInitialize();
destradaafb23c672015-04-16 14:01:27 -07002043 break;
Wyatt Riley26465d22018-02-12 13:44:24 -08002044 case REPORT_LOCATION:
2045 handleReportLocation(msg.arg1 == 1, (Location) msg.obj);
2046 break;
2047 case REPORT_SV_STATUS:
2048 handleReportSvStatus((SvStatusInfo) msg.obj);
2049 break;
Kweku Adams810c77d2019-08-28 07:45:00 -07002050 case UPDATE_LOW_POWER_MODE:
2051 updateLowPowerMode();
2052 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002054 if (msg.arg2 == 1) {
2055 // wakelock was taken for this message, release it
2056 mWakeLock.release();
Anil Admal4f97c942018-11-12 10:52:46 -08002057 if (DEBUG) {
2058 Log.d(TAG, "WakeLock released by handleMessage(" + messageIdAsString(message)
Wyatt Rileycf879db2017-01-12 13:57:38 -08002059 + ", " + msg.arg1 + ", " + msg.obj + ")");
2060 }
Mike Lockwood98e48692010-04-07 16:32:51 -04002061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 }
destradaafb23c672015-04-16 14:01:27 -07002063
2064 /**
Soonil Nagarkar1575a042018-10-24 17:54:54 -07002065 * This method is bound to {@link #GnssLocationProvider(Context, LocationProviderManager,
2066 * Looper)}.
destradaafb23c672015-04-16 14:01:27 -07002067 * It is in charge of loading properties and registering for events that will be posted to
2068 * this handler.
2069 */
destradaae21252a2015-09-08 12:32:59 -07002070 private void handleInitialize() {
Anil Admal0c2b21bd2019-05-03 18:29:02 -07002071 // class_init_native() already initializes the GNSS service handle during class loading.
2072 setupNativeGnssService(/* reinitializeGnssServiceHandle = */ false);
Wyatt Riley523a0cf2017-10-31 14:36:52 -07002073
Anil Admal94ec76a2019-01-15 09:42:01 -08002074 if (native_is_gnss_visibility_control_supported()) {
Anil Admal8a246a22019-05-05 00:34:55 -07002075 mGnssVisibilityControl = new GnssVisibilityControl(mContext, mLooper, mNIHandler);
Anil Admal94ec76a2019-01-15 09:42:01 -08002076 }
2077
destradaafb23c672015-04-16 14:01:27 -07002078 // load default GPS configuration
2079 // (this configuration might change in the future based on SIM changes)
Anil Admald71cf142018-12-21 14:59:36 -08002080 reloadGpsProperties();
destradaafb23c672015-04-16 14:01:27 -07002081
destradaafb23c672015-04-16 14:01:27 -07002082 // listen for events
WyattRiley6593cf12018-06-23 10:37:48 -07002083 IntentFilter intentFilter = new IntentFilter();
destradaafb23c672015-04-16 14:01:27 -07002084 intentFilter.addAction(ALARM_WAKEUP);
2085 intentFilter.addAction(ALARM_TIMEOUT);
destradaafb23c672015-04-16 14:01:27 -07002086 intentFilter.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
Adam Lesinski87c17df2015-05-27 13:24:13 -07002087 intentFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
destradaafb23c672015-04-16 14:01:27 -07002088 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
2089 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
Meng Wang19b214d2018-11-07 12:14:39 -08002090 intentFilter.addAction(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
Anil Admale1539e82019-05-09 15:05:04 -07002091 intentFilter.addAction(TelephonyIntents.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED);
destradaafb23c672015-04-16 14:01:27 -07002092 mContext.registerReceiver(mBroadcastReceiver, intentFilter, null, this);
2093
Anil Admal50ba15e2018-11-01 16:42:42 -07002094 mNetworkConnectivityHandler.registerNetworkCallbacks();
destradaae21252a2015-09-08 12:32:59 -07002095
destradaafb23c672015-04-16 14:01:27 -07002096 // listen for PASSIVE_PROVIDER updates
2097 LocationManager locManager =
2098 (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
2099 long minTime = 0;
2100 float minDistance = 0;
destradaafb23c672015-04-16 14:01:27 -07002101 LocationRequest request = LocationRequest.createFromDeprecatedProvider(
2102 LocationManager.PASSIVE_PROVIDER,
2103 minTime,
2104 minDistance,
Soonil Nagarkar1575a042018-10-24 17:54:54 -07002105 false);
destradaafb23c672015-04-16 14:01:27 -07002106 // Don't keep track of this request since it's done on behalf of other clients
2107 // (which are kept track of separately).
2108 request.setHideFromAppOps(true);
2109 locManager.requestLocationUpdates(
2110 request,
2111 new NetworkLocationListener(),
2112 getLooper());
Soonil Nagarkar1575a042018-10-24 17:54:54 -07002113
Soonil Nagarkar35c3b912019-01-31 10:31:24 -08002114 updateEnabled();
destradaafb23c672015-04-16 14:01:27 -07002115 }
2116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117
Yu-Han Yange7baef32018-02-09 13:58:17 -08002118 private abstract class LocationChangeListener implements LocationListener {
Soonil Nagarkar1575a042018-10-24 17:54:54 -07002119 private int mNumLocationUpdateRequest;
Yu-Han Yang07561382018-02-21 13:08:37 -08002120
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002121 @Override
gomo48f1a642017-11-10 20:35:46 -08002122 public void onStatusChanged(String provider, int status, Bundle extras) {
2123 }
2124
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002125 @Override
gomo48f1a642017-11-10 20:35:46 -08002126 public void onProviderEnabled(String provider) {
2127 }
2128
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002129 @Override
gomo48f1a642017-11-10 20:35:46 -08002130 public void onProviderDisabled(String provider) {
2131 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002132 }
2133
Yu-Han Yange7baef32018-02-09 13:58:17 -08002134 private final class NetworkLocationListener extends LocationChangeListener {
2135 @Override
2136 public void onLocationChanged(Location location) {
2137 // this callback happens on mHandler looper
2138 if (LocationManager.NETWORK_PROVIDER.equals(location.getProvider())) {
Anil Admal2ac70462019-06-28 19:17:41 -07002139 injectLocation(location);
Yu-Han Yange7baef32018-02-09 13:58:17 -08002140 }
2141 }
2142 }
2143
2144 private final class FusedLocationListener extends LocationChangeListener {
2145 @Override
2146 public void onLocationChanged(Location location) {
2147 if (LocationManager.FUSED_PROVIDER.equals(location.getProvider())) {
Yu-Han Yange7baef32018-02-09 13:58:17 -08002148 injectBestLocation(location);
2149 }
2150 }
2151 }
2152
Wyatt Rileycf879db2017-01-12 13:57:38 -08002153 /**
2154 * @return A string representing the given message ID.
2155 */
2156 private String messageIdAsString(int message) {
2157 switch (message) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002158 case SET_REQUEST:
2159 return "SET_REQUEST";
Wyatt Rileycf879db2017-01-12 13:57:38 -08002160 case INJECT_NTP_TIME:
2161 return "INJECT_NTP_TIME";
Yu-Han Yange7baef32018-02-09 13:58:17 -08002162 case REQUEST_LOCATION:
2163 return "REQUEST_LOCATION";
Kevin Tang8c6ac672019-03-22 12:31:01 -07002164 case DOWNLOAD_PSDS_DATA:
2165 return "DOWNLOAD_PSDS_DATA";
2166 case DOWNLOAD_PSDS_DATA_FINISHED:
2167 return "DOWNLOAD_PSDS_DATA_FINISHED";
Wyatt Rileycf879db2017-01-12 13:57:38 -08002168 case INITIALIZE_HANDLER:
2169 return "INITIALIZE_HANDLER";
Wyatt Riley26465d22018-02-12 13:44:24 -08002170 case REPORT_LOCATION:
2171 return "REPORT_LOCATION";
2172 case REPORT_SV_STATUS:
2173 return "REPORT_SV_STATUS";
Wyatt Rileycf879db2017-01-12 13:57:38 -08002174 default:
2175 return "<Unknown>";
2176 }
2177 }
2178
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002179 @Override
2180 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2181 StringBuilder s = new StringBuilder();
Soonil Nagarkar1c572552019-07-10 13:31:47 -07002182 s.append("mStarted=").append(mStarted).append(" (changed ");
WyattRileyba6072f2019-04-18 07:37:52 -07002183 TimeUtils.formatDuration(SystemClock.elapsedRealtime()
2184 - mStartedChangedElapsedRealtime, s);
2185 s.append(" ago)").append('\n');
Soonil Nagarkar1c572552019-07-10 13:31:47 -07002186 s.append("mFixInterval=").append(mFixInterval).append('\n');
2187 s.append("mLowPowerMode=").append(mLowPowerMode).append('\n');
2188 s.append("mGnssMeasurementsProvider.isRegistered()=")
Wyatt Riley74479bd2018-01-17 08:48:27 -08002189 .append(mGnssMeasurementsProvider.isRegistered()).append('\n');
Soonil Nagarkar1c572552019-07-10 13:31:47 -07002190 s.append("mGnssNavigationMessageProvider.isRegistered()=")
Wyatt Riley74479bd2018-01-17 08:48:27 -08002191 .append(mGnssNavigationMessageProvider.isRegistered()).append('\n');
Soonil Nagarkar1c572552019-07-10 13:31:47 -07002192 s.append("mDisableGpsForPowerManager=").append(mDisableGpsForPowerManager).append('\n');
2193 s.append("mTopHalCapabilities=0x").append(Integer.toHexString(mTopHalCapabilities));
destradaa25e8caf2015-08-24 14:14:44 -07002194 s.append(" ( ");
2195 if (hasCapability(GPS_CAPABILITY_SCHEDULING)) s.append("SCHEDULING ");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002196 if (hasCapability(GPS_CAPABILITY_MSB)) s.append("MSB ");
2197 if (hasCapability(GPS_CAPABILITY_MSA)) s.append("MSA ");
2198 if (hasCapability(GPS_CAPABILITY_SINGLE_SHOT)) s.append("SINGLE_SHOT ");
2199 if (hasCapability(GPS_CAPABILITY_ON_DEMAND_TIME)) s.append("ON_DEMAND_TIME ");
destradaa25e8caf2015-08-24 14:14:44 -07002200 if (hasCapability(GPS_CAPABILITY_GEOFENCING)) s.append("GEOFENCING ");
2201 if (hasCapability(GPS_CAPABILITY_MEASUREMENTS)) s.append("MEASUREMENTS ");
2202 if (hasCapability(GPS_CAPABILITY_NAV_MESSAGES)) s.append("NAV_MESSAGES ");
Anil Admalefd9dc62019-03-12 17:39:20 -07002203 if (hasCapability(GPS_CAPABILITY_LOW_POWER_MODE)) s.append("LOW_POWER_MODE ");
2204 if (hasCapability(GPS_CAPABILITY_SATELLITE_BLACKLIST)) s.append("SATELLITE_BLACKLIST ");
Anil Admal62c42dc2019-04-03 15:39:22 -07002205 if (hasCapability(GPS_CAPABILITY_MEASUREMENT_CORRECTIONS)) {
2206 s.append("MEASUREMENT_CORRECTIONS ");
2207 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002208 s.append(")\n");
Anil Admal3ba0fa92019-04-19 17:43:00 -07002209 if (hasCapability(GPS_CAPABILITY_MEASUREMENT_CORRECTIONS)) {
Soonil Nagarkar1c572552019-07-10 13:31:47 -07002210 s.append("SubHal=MEASUREMENT_CORRECTIONS[");
Anil Admalefd9dc62019-03-12 17:39:20 -07002211 s.append(mGnssMeasurementCorrectionsProvider.toStringCapabilities());
2212 s.append("]\n");
2213 }
Siddharth Raybb608c82017-03-16 11:33:34 -07002214 s.append(mGnssMetrics.dumpGnssMetricsAsText());
Soonil Nagarkar1c572552019-07-10 13:31:47 -07002215 s.append("native internal state: \n");
2216 s.append(" ").append(native_get_internal_state());
Wyatt Rileycf879db2017-01-12 13:57:38 -08002217 s.append("\n");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002218 pw.append(s);
2219 }
2220
Anil Admal0c2b21bd2019-05-03 18:29:02 -07002221 private void setupNativeGnssService(boolean reinitializeGnssServiceHandle) {
2222 native_init_once(reinitializeGnssServiceHandle);
Anil Admal7e3953b2019-05-04 20:45:22 -07002223
2224 /*
2225 * A cycle of native_init() and native_cleanup() is needed so that callbacks are
2226 * registered after bootup even when location is disabled.
2227 * This will allow Emergency SUPL to work even when location is disabled before device
2228 * restart.
2229 */
2230 boolean isInitialized = native_init();
2231 if (!isInitialized) {
2232 Log.w(TAG, "Native initialization failed.");
2233 } else {
2234 native_cleanup();
2235 }
2236 }
2237
Mike Lockwoodb16e7802009-08-06 09:26:02 -04002238 // preallocated to avoid memory allocation in reportNmea()
2239 private byte[] mNmeaBuffer = new byte[120];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 private static native void class_init_native();
gomo48f1a642017-11-10 20:35:46 -08002242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002243 private static native boolean native_is_supported();
gomo48f1a642017-11-10 20:35:46 -08002244
Anil Admal94ec76a2019-01-15 09:42:01 -08002245 private static native boolean native_is_gnss_visibility_control_supported();
2246
Anil Admal0c2b21bd2019-05-03 18:29:02 -07002247 private static native void native_init_once(boolean reinitializeGnssServiceHandle);
Yu-Han Yang6d317352018-03-15 11:53:01 -07002248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 private native boolean native_init();
gomo48f1a642017-11-10 20:35:46 -08002250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002251 private native void native_cleanup();
gomo48f1a642017-11-10 20:35:46 -08002252
Mike Lockwood04598b62010-04-14 17:17:24 -04002253 private native boolean native_set_position_mode(int mode, int recurrence, int min_interval,
gomo48f1a642017-11-10 20:35:46 -08002254 int preferred_accuracy, int preferred_time, boolean lowPowerMode);
2255
Mike Lockwood04598b62010-04-14 17:17:24 -04002256 private native boolean native_start();
gomo48f1a642017-11-10 20:35:46 -08002257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 private native boolean native_stop();
gomo48f1a642017-11-10 20:35:46 -08002259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 private native void native_delete_aiding_data(int flags);
gomo48f1a642017-11-10 20:35:46 -08002261
Mike Lockwoodf602d362010-06-20 14:28:16 -07002262 private native int native_read_nmea(byte[] buffer, int bufferSize);
gomo48f1a642017-11-10 20:35:46 -08002263
Yu-Han Yange7baef32018-02-09 13:58:17 -08002264 private native void native_inject_best_location(
Pierre Fite-Georgelb50cdaf2019-02-25 15:42:45 -08002265 int gnssLocationFlags, double latitudeDegrees, double longitudeDegrees,
2266 double altitudeMeters, float speedMetersPerSec, float bearingDegrees,
2267 float horizontalAccuracyMeters, float verticalAccuracyMeters,
2268 float speedAccuracyMetersPerSecond, float bearingAccuracyDegrees,
Pierre Fite-Georgel9e96c572019-02-25 16:12:53 -08002269 long timestamp, int elapsedRealtimeFlags, long elapsedRealtimeNanos,
Yu-Han Yang3cd9a862019-03-25 17:00:03 -07002270 double elapsedRealtimeUncertaintyNanos);
Yu-Han Yange7baef32018-02-09 13:58:17 -08002271
Mike Lockwoodd26ce0d2009-06-11 12:25:46 -04002272 private native void native_inject_location(double latitude, double longitude, float accuracy);
2273
Kevin Tang8c6ac672019-03-22 12:31:01 -07002274 // PSDS Support
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 private native void native_inject_time(long time, long timeReference, int uncertainty);
gomo48f1a642017-11-10 20:35:46 -08002276
Kevin Tang8c6ac672019-03-22 12:31:01 -07002277 private native boolean native_supports_psds();
gomo48f1a642017-11-10 20:35:46 -08002278
Kevin Tang8c6ac672019-03-22 12:31:01 -07002279 private native void native_inject_psds_data(byte[] data, int length);
The Android Open Source Project10592532009-03-18 17:39:46 -07002280
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002281 // DEBUG Support
2282 private native String native_get_internal_state();
2283
2284 // AGPS Support
gomo48f1a642017-11-10 20:35:46 -08002285 private native void native_agps_ni_message(byte[] msg, int length);
2286
Mike Lockwooda9e54612009-06-19 14:54:42 -04002287 private native void native_set_agps_server(int type, String hostname, int port);
Danke Xie22d1f9f2009-08-18 18:28:45 -04002288
2289 // Network-initiated (NI) Support
2290 private native void native_send_ni_response(int notificationId, int userResponse);
Miguel Torroja1e84da82010-07-27 07:02:24 +02002291
Anil Admal50ba15e2018-11-01 16:42:42 -07002292 // AGPS ril support
Miguel Torroja1e84da82010-07-27 07:02:24 +02002293 private native void native_agps_set_ref_location_cellid(int type, int mcc, int mnc,
2294 int lac, int cid);
gomo48f1a642017-11-10 20:35:46 -08002295
Miguel Torroja1e84da82010-07-27 07:02:24 +02002296 private native void native_agps_set_id(int type, String setid);
Pierre Fite-Georgelb50cdaf2019-02-25 15:42:45 -08002297}