blob: c84745e8464641d996e412f27ef222affa835835 [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,
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08001172 newWork.getUid(i), newWork.getPackageName(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++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08001179 mAppOps.finishOp(AppOpsManager.OP_GPS, goneWork.getUid(i),
1180 goneWork.getPackageName(i));
Dianne Hackborn2e418422009-06-22 20:00:17 -07001181 }
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001182 }
1183 }
1184 }
1185
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001186 @Override
Soonil Nagarkard334f7b2019-07-08 16:16:19 -07001187 public void onSendExtraCommand(int uid, int pid, String command, Bundle extras) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001188
Mike Lockwood63aa5a62010-04-14 19:21:31 -04001189 long identity = Binder.clearCallingIdentity();
Peter Visontayb25db362017-11-01 18:18:12 +00001190 try {
Peter Visontayb25db362017-11-01 18:18:12 +00001191 if ("delete_aiding_data".equals(command)) {
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001192 deleteAidingData(extras);
Peter Visontayb25db362017-11-01 18:18:12 +00001193 } else if ("force_time_injection".equals(command)) {
1194 requestUtcTime();
Kevin Tang8c6ac672019-03-22 12:31:01 -07001195 } else if ("force_psds_injection".equals(command)) {
1196 if (mSupportsPsds) {
1197 psdsDownloadRequest();
Peter Visontayb25db362017-11-01 18:18:12 +00001198 }
1199 } else {
1200 Log.w(TAG, "sendExtraCommand: unknown command " + command);
Mike Lockwood93bc44d2009-05-20 16:58:22 -04001201 }
Peter Visontayb25db362017-11-01 18:18:12 +00001202 } finally {
1203 Binder.restoreCallingIdentity(identity);
Mike Lockwood93bc44d2009-05-20 16:58:22 -04001204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 }
1206
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001207 private void deleteAidingData(Bundle extras) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 int flags;
1209
1210 if (extras == null) {
1211 flags = GPS_DELETE_ALL;
1212 } else {
1213 flags = 0;
1214 if (extras.getBoolean("ephemeris")) flags |= GPS_DELETE_EPHEMERIS;
1215 if (extras.getBoolean("almanac")) flags |= GPS_DELETE_ALMANAC;
1216 if (extras.getBoolean("position")) flags |= GPS_DELETE_POSITION;
1217 if (extras.getBoolean("time")) flags |= GPS_DELETE_TIME;
1218 if (extras.getBoolean("iono")) flags |= GPS_DELETE_IONO;
1219 if (extras.getBoolean("utc")) flags |= GPS_DELETE_UTC;
1220 if (extras.getBoolean("health")) flags |= GPS_DELETE_HEALTH;
1221 if (extras.getBoolean("svdir")) flags |= GPS_DELETE_SVDIR;
1222 if (extras.getBoolean("svsteer")) flags |= GPS_DELETE_SVSTEER;
1223 if (extras.getBoolean("sadata")) flags |= GPS_DELETE_SADATA;
1224 if (extras.getBoolean("rti")) flags |= GPS_DELETE_RTI;
1225 if (extras.getBoolean("celldb-info")) flags |= GPS_DELETE_CELLDB_INFO;
1226 if (extras.getBoolean("all")) flags |= GPS_DELETE_ALL;
1227 }
1228
1229 if (flags != 0) {
1230 native_delete_aiding_data(flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 }
1233
Yu-Han Yang6a5f0b72019-01-24 18:34:28 -08001234 private void startNavigating() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 if (!mStarted) {
Yu-Han Yang6a5f0b72019-01-24 18:34:28 -08001236 if (DEBUG) Log.d(TAG, "startNavigating");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001237 mTimeToFirstFix = 0;
1238 mLastFixTime = 0;
WyattRileyba6072f2019-04-18 07:37:52 -07001239 setStarted(true);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001240 mPositionMode = GPS_POSITION_MODE_STANDALONE;
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001241 // Notify about suppressed output, if speed limit was previously exceeded.
1242 // Elsewhere, we check again with every speed output reported.
1243 if (mItarSpeedLimitExceeded) {
1244 Log.i(TAG, "startNavigating with ITAR limit in place. Output limited " +
1245 "until slow enough speed reported.");
1246 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001247
Tsuwei Chen462bcd82014-09-17 12:28:49 -07001248 boolean agpsEnabled =
1249 (Settings.Global.getInt(mContext.getContentResolver(),
gomo48f1a642017-11-10 20:35:46 -08001250 Settings.Global.ASSISTED_GPS_ENABLED, 1) != 0);
Yu-Han Yang6a5f0b72019-01-24 18:34:28 -08001251 mPositionMode = getSuplMode(agpsEnabled);
Mike Lockwoodbcab8df2009-06-25 16:39:09 -04001252
Stan Chesnutt1d72d8c2013-04-15 19:18:02 -07001253 if (DEBUG) {
1254 String mode;
1255
gomo48f1a642017-11-10 20:35:46 -08001256 switch (mPositionMode) {
Stan Chesnutt1d72d8c2013-04-15 19:18:02 -07001257 case GPS_POSITION_MODE_STANDALONE:
1258 mode = "standalone";
1259 break;
1260 case GPS_POSITION_MODE_MS_ASSISTED:
1261 mode = "MS_ASSISTED";
1262 break;
1263 case GPS_POSITION_MODE_MS_BASED:
1264 mode = "MS_BASED";
1265 break;
1266 default:
1267 mode = "unknown";
1268 break;
1269 }
1270 Log.d(TAG, "setting position_mode to " + mode);
1271 }
1272
Mike Lockwood04598b62010-04-14 17:17:24 -04001273 int interval = (hasCapability(GPS_CAPABILITY_SCHEDULING) ? mFixInterval : 1000);
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001274 mLowPowerMode = mProviderRequest.lowPowerMode;
Yu-Han Yangc8b9ff72018-04-17 00:47:24 -07001275 if (!setPositionMode(mPositionMode, GPS_POSITION_RECURRENCE_PERIODIC,
gomo48f1a642017-11-10 20:35:46 -08001276 interval, 0, 0, mLowPowerMode)) {
WyattRileyba6072f2019-04-18 07:37:52 -07001277 setStarted(false);
Mike Lockwood04598b62010-04-14 17:17:24 -04001278 Log.e(TAG, "set_position_mode failed in startNavigating()");
1279 return;
1280 }
1281 if (!native_start()) {
WyattRileyba6072f2019-04-18 07:37:52 -07001282 setStarted(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 Log.e(TAG, "native_start failed in startNavigating()");
Mike Lockwood0632ca72009-05-14 15:51:03 -04001284 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 }
1286
1287 // reset SV count to zero
Wyatt Rileyc7067412018-02-07 15:50:35 -08001288 mLocationExtras.reset();
Yipeng Cao282b5942017-05-17 20:31:39 -07001289 mFixRequestTime = SystemClock.elapsedRealtime();
Mike Lockwood04598b62010-04-14 17:17:24 -04001290 if (!hasCapability(GPS_CAPABILITY_SCHEDULING)) {
1291 // set timer to give up if we do not receive a fix within NO_FIX_TIMEOUT
1292 // and our fix interval is not short
1293 if (mFixInterval >= NO_FIX_TIMEOUT) {
1294 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1295 SystemClock.elapsedRealtime() + NO_FIX_TIMEOUT, mTimeoutIntent);
1296 }
Mike Lockwood0632ca72009-05-14 15:51:03 -04001297 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 }
1299 }
1300
Mike Lockwood62a8fc12010-03-22 14:23:26 -04001301 private void stopNavigating() {
Mike Lockwood29c84342009-05-06 14:01:15 -04001302 if (DEBUG) Log.d(TAG, "stopNavigating");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 if (mStarted) {
WyattRileyba6072f2019-04-18 07:37:52 -07001304 setStarted(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 native_stop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 mLastFixTime = 0;
Yu-Han Yanga50cd602018-08-28 12:33:24 -07001307 // native_stop() may reset the position mode in hardware.
1308 mLastPositionMode = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309
1310 // reset SV count to zero
Wyatt Rileyc7067412018-02-07 15:50:35 -08001311 mLocationExtras.reset();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 }
1313 }
1314
WyattRileyba6072f2019-04-18 07:37:52 -07001315 private void setStarted(boolean started) {
1316 if (mStarted != started) {
1317 mStarted = started;
1318 mStartedChangedElapsedRealtime = SystemClock.elapsedRealtime();
1319 }
1320 }
1321
Mike Lockwood0632ca72009-05-14 15:51:03 -04001322 private void hibernate() {
1323 // stop GPS until our next fix interval arrives
1324 stopNavigating();
Mike Lockwood0632ca72009-05-14 15:51:03 -04001325 mAlarmManager.cancel(mTimeoutIntent);
1326 mAlarmManager.cancel(mWakeupIntent);
1327 long now = SystemClock.elapsedRealtime();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001328 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, now + mFixInterval, mWakeupIntent);
Mike Lockwood04598b62010-04-14 17:17:24 -04001329 }
1330
1331 private boolean hasCapability(int capability) {
Anil Admal312fddb2019-03-25 12:15:43 -07001332 return (mTopHalCapabilities & capability) != 0;
Mike Lockwood0632ca72009-05-14 15:51:03 -04001333 }
1334
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001335 @NativeEntryPoint
Wyatt Riley5d229832017-02-10 17:06:00 -08001336 private void reportLocation(boolean hasLatLong, Location location) {
Wyatt Riley26465d22018-02-12 13:44:24 -08001337 sendMessage(REPORT_LOCATION, hasLatLong ? 1 : 0, location);
1338 }
1339
1340 private void handleReportLocation(boolean hasLatLong, Location location) {
Wyatt Riley5d229832017-02-10 17:06:00 -08001341 if (location.hasSpeed()) {
1342 mItarSpeedLimitExceeded = location.getSpeed() > ITAR_SPEED_LIMIT_METERS_PER_SECOND;
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001343 }
1344
1345 if (mItarSpeedLimitExceeded) {
1346 Log.i(TAG, "Hal reported a speed in excess of ITAR limit." +
1347 " GPS/GNSS Navigation output blocked.");
Siddharth Ray53ddc802018-03-16 12:01:52 -07001348 if (mStarted) {
1349 mGnssMetrics.logReceivedLocationStatus(false);
1350 }
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001351 return; // No output of location allowed
1352 }
1353
Wyatt Riley5d229832017-02-10 17:06:00 -08001354 if (VERBOSE) Log.v(TAG, "reportLocation " + location.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355
Wyatt Riley26465d22018-02-12 13:44:24 -08001356 location.setExtras(mLocationExtras.getBundle());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001358 reportLocation(location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359
Siddharth Ray53ddc802018-03-16 12:01:52 -07001360 if (mStarted) {
1361 mGnssMetrics.logReceivedLocationStatus(hasLatLong);
1362 if (hasLatLong) {
1363 if (location.hasAccuracy()) {
1364 mGnssMetrics.logPositionAccuracyMeters(location.getAccuracy());
1365 }
1366 if (mTimeToFirstFix > 0) {
1367 int timeBetweenFixes = (int) (SystemClock.elapsedRealtime() - mLastFixTime);
1368 mGnssMetrics.logMissedReports(mFixInterval, timeBetweenFixes);
1369 }
Siddharth Raybb608c82017-03-16 11:33:34 -07001370 }
WyattRileyba6072f2019-04-18 07:37:52 -07001371 } else {
1372 // Warn or error about long delayed GNSS engine shutdown as this generally wastes
1373 // power and sends location when not expected.
1374 long locationAfterStartedFalseMillis =
1375 SystemClock.elapsedRealtime() - mStartedChangedElapsedRealtime;
1376 if (locationAfterStartedFalseMillis > LOCATION_OFF_DELAY_THRESHOLD_WARN_MILLIS) {
1377 String logMessage = "Unexpected GNSS Location report "
1378 + TimeUtils.formatDuration(locationAfterStartedFalseMillis)
1379 + " after location turned off";
1380 if (locationAfterStartedFalseMillis > LOCATION_OFF_DELAY_THRESHOLD_ERROR_MILLIS) {
1381 Log.e(TAG, logMessage);
1382 } else {
1383 Log.w(TAG, logMessage);
1384 }
1385 }
Siddharth Raybb608c82017-03-16 11:33:34 -07001386 }
1387
Yipeng Cao282b5942017-05-17 20:31:39 -07001388 mLastFixTime = SystemClock.elapsedRealtime();
Hakan Gustavssonfa94ff02010-02-23 09:12:38 +01001389 // report time to first fix
Wyatt Riley5d229832017-02-10 17:06:00 -08001390 if (mTimeToFirstFix == 0 && hasLatLong) {
gomo48f1a642017-11-10 20:35:46 -08001391 mTimeToFirstFix = (int) (mLastFixTime - mFixRequestTime);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001392 if (DEBUG) Log.d(TAG, "TTFF: " + mTimeToFirstFix);
Siddharth Ray53ddc802018-03-16 12:01:52 -07001393 if (mStarted) {
1394 mGnssMetrics.logTimeToFirstFixMilliSecs(mTimeToFirstFix);
1395 }
Hakan Gustavssonfa94ff02010-02-23 09:12:38 +01001396
1397 // notify status listeners
Anil Admal75b9fd62018-11-28 11:22:50 -08001398 mGnssStatusListenerHelper.onFirstFix(mTimeToFirstFix);
Hakan Gustavssonfa94ff02010-02-23 09:12:38 +01001399 }
1400
Soonil Nagarkarfc9c7f82019-07-16 12:07:57 -07001401 if (mStarted) {
Wyatt Rileyc7067412018-02-07 15:50:35 -08001402 // For devices that use framework scheduling, a timer may be set to ensure we don't
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001403 // spend too much power searching for a location, when the requested update rate is
1404 // slow.
Wyatt Rileyc7067412018-02-07 15:50:35 -08001405 // As we just recievied a location, we'll cancel that timer.
Mike Lockwood04598b62010-04-14 17:17:24 -04001406 if (!hasCapability(GPS_CAPABILITY_SCHEDULING) && mFixInterval < NO_FIX_TIMEOUT) {
Mike Lockwoodb7be5442010-02-24 14:34:50 -05001407 mAlarmManager.cancel(mTimeoutIntent);
1408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 }
Mike Lockwood29c84342009-05-06 14:01:15 -04001410
gomo48f1a642017-11-10 20:35:46 -08001411 if (!hasCapability(GPS_CAPABILITY_SCHEDULING) && mStarted &&
1412 mFixInterval > GPS_POLLING_THRESHOLD_INTERVAL) {
Mike Lockwoodd53ba012010-04-15 20:41:26 -04001413 if (DEBUG) Log.d(TAG, "got fix, hibernating");
Mike Lockwood0632ca72009-05-14 15:51:03 -04001414 hibernate();
Mike Lockwood29c84342009-05-06 14:01:15 -04001415 }
gomo48f1a642017-11-10 20:35:46 -08001416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001418 @NativeEntryPoint
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 private void reportStatus(int status) {
Mike Lockwoodb8d90332010-10-18 17:59:48 -04001420 if (DEBUG) Log.v(TAG, "reportStatus status: " + status);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421
destradaaea8a8a62014-06-23 18:19:03 -07001422 boolean wasNavigating = mNavigating;
1423 switch (status) {
1424 case GPS_STATUS_SESSION_BEGIN:
1425 mNavigating = true;
destradaaea8a8a62014-06-23 18:19:03 -07001426 break;
1427 case GPS_STATUS_SESSION_END:
1428 mNavigating = false;
1429 break;
1430 case GPS_STATUS_ENGINE_ON:
destradaaea8a8a62014-06-23 18:19:03 -07001431 break;
1432 case GPS_STATUS_ENGINE_OFF:
destradaaea8a8a62014-06-23 18:19:03 -07001433 mNavigating = false;
1434 break;
1435 }
Mike Lockwooddbd6fd82009-12-07 18:43:36 -05001436
destradaaea8a8a62014-06-23 18:19:03 -07001437 if (wasNavigating != mNavigating) {
Anil Admal75b9fd62018-11-28 11:22:50 -08001438 mGnssStatusListenerHelper.onStatusChanged(mNavigating);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
1440 }
1441
Wyatt Riley26465d22018-02-12 13:44:24 -08001442 // Helper class to carry data to handler for reportSvStatus
1443 private static class SvStatusInfo {
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001444 private int mSvCount;
1445 private int[] mSvidWithFlags;
1446 private float[] mCn0s;
1447 private float[] mSvElevations;
1448 private float[] mSvAzimuths;
1449 private float[] mSvCarrierFreqs;
Wyatt Riley26465d22018-02-12 13:44:24 -08001450 }
1451
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001452 @NativeEntryPoint
Wyatt Riley26465d22018-02-12 13:44:24 -08001453 private void reportSvStatus(int svCount, int[] svidWithFlags, float[] cn0s,
1454 float[] svElevations, float[] svAzimuths, float[] svCarrierFreqs) {
1455 SvStatusInfo svStatusInfo = new SvStatusInfo();
1456 svStatusInfo.mSvCount = svCount;
1457 svStatusInfo.mSvidWithFlags = svidWithFlags;
1458 svStatusInfo.mCn0s = cn0s;
1459 svStatusInfo.mSvElevations = svElevations;
1460 svStatusInfo.mSvAzimuths = svAzimuths;
1461 svStatusInfo.mSvCarrierFreqs = svCarrierFreqs;
1462
1463 sendMessage(REPORT_SV_STATUS, 0, svStatusInfo);
1464 }
1465
1466 private void handleReportSvStatus(SvStatusInfo info) {
Anil Admal75b9fd62018-11-28 11:22:50 -08001467 mGnssStatusListenerHelper.onSvStatusChanged(
Wyatt Riley26465d22018-02-12 13:44:24 -08001468 info.mSvCount,
1469 info.mSvidWithFlags,
1470 info.mCn0s,
1471 info.mSvElevations,
1472 info.mSvAzimuths,
1473 info.mSvCarrierFreqs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474
Siddharth Ray168f12a2017-07-10 11:55:10 -07001475 // Log CN0 as part of GNSS metrics
Blake Kragtenbb613602019-08-28 16:21:35 -07001476 mGnssMetrics.logCn0(info.mCn0s, info.mSvCount, info.mSvCarrierFreqs);
Siddharth Ray168f12a2017-07-10 11:55:10 -07001477
Mike Lockwood29c84342009-05-06 14:01:15 -04001478 if (VERBOSE) {
Wyatt Riley26465d22018-02-12 13:44:24 -08001479 Log.v(TAG, "SV count: " + info.mSvCount);
Lifu Tang30f95a72016-01-07 23:20:38 -08001480 }
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001481 // Calculate number of satellites used in fix.
Soonil Nagarkar0d1890b2019-11-12 12:13:14 -08001482 GnssStatus gnssStatus = GnssStatus.wrap(
1483 info.mSvCount,
1484 info.mSvidWithFlags,
1485 info.mCn0s,
1486 info.mSvElevations,
1487 info.mSvAzimuths,
1488 info.mSvCarrierFreqs);
Lifu Tang30f95a72016-01-07 23:20:38 -08001489 int usedInFixCount = 0;
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001490 int maxCn0 = 0;
1491 int meanCn0 = 0;
Soonil Nagarkar0d1890b2019-11-12 12:13:14 -08001492 for (int i = 0; i < gnssStatus.getSatelliteCount(); i++) {
1493 if (gnssStatus.usedInFix(i)) {
Lifu Tang30f95a72016-01-07 23:20:38 -08001494 ++usedInFixCount;
Soonil Nagarkar0d1890b2019-11-12 12:13:14 -08001495 if (gnssStatus.getCn0DbHz(i) > maxCn0) {
1496 maxCn0 = (int) gnssStatus.getCn0DbHz(i);
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001497 }
Soonil Nagarkar0d1890b2019-11-12 12:13:14 -08001498 meanCn0 += gnssStatus.getCn0DbHz(i);
1499 mGnssMetrics.logConstellationType(gnssStatus.getConstellationType(i));
Lifu Tang30f95a72016-01-07 23:20:38 -08001500 }
1501 if (VERBOSE) {
Soonil Nagarkar0d1890b2019-11-12 12:13:14 -08001502 Log.v(TAG, "svid: " + gnssStatus.getSvid(i)
1503 + " cn0: " + gnssStatus.getCn0DbHz(i)
1504 + " elev: " + gnssStatus.getElevationDegrees(i)
1505 + " azimuth: " + gnssStatus.getAzimuthDegrees(i)
1506 + " carrier frequency: " + gnssStatus.getCn0DbHz(i)
1507 + (gnssStatus.hasEphemerisData(i) ? " E" : " ")
1508 + (gnssStatus.hasAlmanacData(i) ? " A" : " ")
1509 + (gnssStatus.usedInFix(i) ? "U" : "")
1510 + (gnssStatus.hasCarrierFrequencyHz(i) ? "F" : ""));
Yu-Han Yang284234e2019-03-28 19:35:57 -07001511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 }
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001513 if (usedInFixCount > 0) {
1514 meanCn0 /= usedInFixCount;
1515 }
1516 // return number of sats used in fix instead of total reported
Wyatt Rileyc7067412018-02-07 15:50:35 -08001517 mLocationExtras.set(usedInFixCount, meanCn0, maxCn0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518
Soonil Nagarkar0d1890b2019-11-12 12:13:14 -08001519 mGnssMetrics.logSvStatus(gnssStatus);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 }
Mike Lockwood58bda982009-04-14 16:25:07 -04001521
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001522 @NativeEntryPoint
Anil Admalc70344b2018-11-16 14:22:38 -08001523 private void reportAGpsStatus(int agpsType, int agpsStatus, byte[] suplIpAddr) {
1524 mNetworkConnectivityHandler.onReportAGpsStatus(agpsType, agpsStatus, suplIpAddr);
destradaae21252a2015-09-08 12:32:59 -07001525 }
1526
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001527 @NativeEntryPoint
Mike Lockwoodf602d362010-06-20 14:28:16 -07001528 private void reportNmea(long timestamp) {
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001529 if (!mItarSpeedLimitExceeded) {
1530 int length = native_read_nmea(mNmeaBuffer, mNmeaBuffer.length);
1531 String nmea = new String(mNmeaBuffer, 0 /* offset */, length);
Anil Admal75b9fd62018-11-28 11:22:50 -08001532 mGnssStatusListenerHelper.onNmeaReceived(timestamp, nmea);
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001533 }
destradaaea8a8a62014-06-23 18:19:03 -07001534 }
Mike Lockwoodb16e7802009-08-06 09:26:02 -04001535
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001536 @NativeEntryPoint
Lifu Tang818aa2c2016-02-01 01:52:00 -08001537 private void reportMeasurementData(GnssMeasurementsEvent event) {
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001538 if (!mItarSpeedLimitExceeded) {
Wyatt Rileyaa420d52017-07-03 15:14:42 -07001539 // send to handler to allow native to return quickly
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001540 mHandler.post(() -> mGnssMeasurementsProvider.onMeasurementsAvailable(event));
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001541 }
Mike Lockwoodb16e7802009-08-06 09:26:02 -04001542 }
1543
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001544 @NativeEntryPoint
Lifu Tange8abe8e2016-04-01 10:32:05 -07001545 private void reportNavigationMessage(GnssNavigationMessage event) {
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001546 if (!mItarSpeedLimitExceeded) {
Wyatt Rileyaa420d52017-07-03 15:14:42 -07001547 // send to handler to allow native to return quickly
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001548 mHandler.post(() -> mGnssNavigationMessageProvider.onNavigationMessageAvailable(event));
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001549 }
destradaa4b3e3932014-07-21 18:01:47 -07001550 }
1551
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001552 @NativeEntryPoint
Anil Admal62c42dc2019-04-03 15:39:22 -07001553 private void setTopHalCapabilities(int topHalCapabilities) {
Anil Admalefd9dc62019-03-12 17:39:20 -07001554 mHandler.post(() -> {
Anil Admal312fddb2019-03-25 12:15:43 -07001555 mTopHalCapabilities = topHalCapabilities;
Mike Lockwood9b9fb5c2011-06-29 15:09:40 -04001556
Anil Admalefd9dc62019-03-12 17:39:20 -07001557 if (hasCapability(GPS_CAPABILITY_ON_DEMAND_TIME)) {
1558 mNtpTimeHelper.enablePeriodicTimeInjection();
1559 requestUtcTime();
1560 }
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001561
Anil Admal62c42dc2019-04-03 15:39:22 -07001562 mGnssMeasurementsProvider.onCapabilitiesUpdated(
1563 hasCapability(GPS_CAPABILITY_MEASUREMENTS));
1564 mGnssNavigationMessageProvider.onCapabilitiesUpdated(
1565 hasCapability(GPS_CAPABILITY_NAV_MESSAGES));
Anil Admalefd9dc62019-03-12 17:39:20 -07001566 restartRequests();
Anil Admal312fddb2019-03-25 12:15:43 -07001567
Anil Admal62c42dc2019-04-03 15:39:22 -07001568 mGnssCapabilitiesProvider.setTopHalCapabilities(mTopHalCapabilities);
Anil Admalefd9dc62019-03-12 17:39:20 -07001569 });
1570 }
1571
1572 @NativeEntryPoint
Anil Admal312fddb2019-03-25 12:15:43 -07001573 private void setSubHalMeasurementCorrectionsCapabilities(int subHalCapabilities) {
1574 mHandler.post(() -> {
1575 if (!mGnssMeasurementCorrectionsProvider.onCapabilitiesUpdated(subHalCapabilities)) {
1576 return;
1577 }
1578
1579 mGnssCapabilitiesProvider.setSubHalMeasurementCorrectionsCapabilities(
1580 subHalCapabilities);
1581 });
Yu-Han Yang52057622018-04-25 00:51:22 -07001582 }
1583
1584 private void restartRequests() {
1585 Log.i(TAG, "restartRequests");
1586
1587 restartLocationRequest();
1588 mGnssMeasurementsProvider.resumeIfStarted();
1589 mGnssNavigationMessageProvider.resumeIfStarted();
1590 mGnssBatchingProvider.resumeIfStarted();
1591 mGnssGeofenceProvider.resumeIfStarted();
1592 }
1593
1594 private void restartLocationRequest() {
1595 if (DEBUG) Log.d(TAG, "restartLocationRequest");
WyattRileyba6072f2019-04-18 07:37:52 -07001596 setStarted(false);
Yu-Han Yang52057622018-04-25 00:51:22 -07001597 updateRequirements();
1598 }
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001599
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001600 @NativeEntryPoint
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001601 private void setGnssYearOfHardware(final int yearOfHardware) {
1602 // mHardwareYear is simply set here, to be read elsewhere, and is volatile for safe sync
1603 if (DEBUG) Log.d(TAG, "setGnssYearOfHardware called with " + yearOfHardware);
1604 mHardwareYear = yearOfHardware;
Mike Lockwood04598b62010-04-14 17:17:24 -04001605 }
1606
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001607 @NativeEntryPoint
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001608 private void setGnssHardwareModelName(final String modelName) {
1609 // mHardwareModelName is simply set here, to be read elsewhere, and volatile for safe sync
1610 if (DEBUG) Log.d(TAG, "setGnssModelName called with " + modelName);
1611 mHardwareModelName = modelName;
Lifu Tang82f893d2016-01-21 18:15:33 -08001612 }
1613
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001614 @NativeEntryPoint
Yu-Han Yang52057622018-04-25 00:51:22 -07001615 private void reportGnssServiceDied() {
1616 if (DEBUG) Log.d(TAG, "reportGnssServiceDied");
1617 mHandler.post(() -> {
Anil Admal0c2b21bd2019-05-03 18:29:02 -07001618 setupNativeGnssService(/* reinitializeGnssServiceHandle = */ true);
Anil Admal204406f2019-07-23 12:00:23 -07001619 // resend configuration into the restarted HAL service.
1620 reloadGpsProperties();
Yu-Han Yang76f99952019-05-04 17:45:44 -07001621 if (isGpsEnabled()) {
1622 setGpsEnabled(false);
Soonil Nagarkar35c3b912019-01-31 10:31:24 -08001623 updateEnabled();
Yu-Han Yang52057622018-04-25 00:51:22 -07001624 }
1625 });
1626 }
1627
Lifu Tang9363b942016-02-16 18:07:00 -08001628 public interface GnssSystemInfoProvider {
Lifu Tang82f893d2016-01-21 18:15:33 -08001629 /**
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001630 * Returns the year of underlying GPS hardware.
Lifu Tang82f893d2016-01-21 18:15:33 -08001631 */
Lifu Tang9363b942016-02-16 18:07:00 -08001632 int getGnssYearOfHardware();
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001633
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001634 /**
1635 * Returns the model name of underlying GPS hardware.
1636 */
1637 String getGnssHardwareModelName();
Lifu Tang82f893d2016-01-21 18:15:33 -08001638 }
1639
1640 /**
1641 * @hide
1642 */
Lifu Tang9363b942016-02-16 18:07:00 -08001643 public GnssSystemInfoProvider getGnssSystemInfoProvider() {
1644 return new GnssSystemInfoProvider() {
Lifu Tang82f893d2016-01-21 18:15:33 -08001645 @Override
Lifu Tang9363b942016-02-16 18:07:00 -08001646 public int getGnssYearOfHardware() {
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001647 return mHardwareYear;
1648 }
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001649
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001650 @Override
1651 public String getGnssHardwareModelName() {
1652 return mHardwareModelName;
Lifu Tang82f893d2016-01-21 18:15:33 -08001653 }
1654 };
1655 }
1656
Wyatt Rileycf879db2017-01-12 13:57:38 -08001657 /**
1658 * @hide
1659 */
1660 public GnssBatchingProvider getGnssBatchingProvider() {
Yu-Han Yang3557cc72018-03-21 12:48:36 -07001661 return mGnssBatchingProvider;
Wyatt Rileycf879db2017-01-12 13:57:38 -08001662 }
1663
Siddharth Raybb608c82017-03-16 11:33:34 -07001664 public interface GnssMetricsProvider {
1665 /**
1666 * Returns GNSS metrics as proto string
1667 */
1668 String getGnssMetricsAsProtoString();
1669 }
1670
1671 /**
1672 * @hide
1673 */
1674 public GnssMetricsProvider getGnssMetricsProvider() {
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001675 return () -> mGnssMetrics.dumpGnssMetricsAsProtoString();
Siddharth Raybb608c82017-03-16 11:33:34 -07001676 }
1677
Anil Admal312fddb2019-03-25 12:15:43 -07001678 /**
1679 * @hide
1680 */
1681 public GnssCapabilitiesProvider getGnssCapabilitiesProvider() {
1682 return mGnssCapabilitiesProvider;
1683 }
1684
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001685 @NativeEntryPoint
Wyatt Rileycf879db2017-01-12 13:57:38 -08001686 private void reportLocationBatch(Location[] locationArray) {
1687 List<Location> locations = new ArrayList<>(Arrays.asList(locationArray));
gomo48f1a642017-11-10 20:35:46 -08001688 if (DEBUG) {
1689 Log.d(TAG, "Location batch of size " + locationArray.length + " reported");
1690 }
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001691 reportLocation(locations);
Wyatt Rileycf879db2017-01-12 13:57:38 -08001692 }
1693
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001694 @NativeEntryPoint
Kevin Tang8c6ac672019-03-22 12:31:01 -07001695 private void psdsDownloadRequest() {
1696 if (DEBUG) Log.d(TAG, "psdsDownloadRequest");
1697 sendMessage(DOWNLOAD_PSDS_DATA, 0, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 }
1699
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001700 /**
destradaa0682809a2013-08-12 18:50:30 -07001701 * Converts the GPS HAL status to the internal Geofence Hardware status.
1702 */
Yu-Han Yang6dc9f052018-12-04 17:11:24 -08001703 private static int getGeofenceStatus(int status) {
gomo48f1a642017-11-10 20:35:46 -08001704 switch (status) {
destradaa0682809a2013-08-12 18:50:30 -07001705 case GPS_GEOFENCE_OPERATION_SUCCESS:
1706 return GeofenceHardware.GEOFENCE_SUCCESS;
1707 case GPS_GEOFENCE_ERROR_GENERIC:
1708 return GeofenceHardware.GEOFENCE_FAILURE;
1709 case GPS_GEOFENCE_ERROR_ID_EXISTS:
1710 return GeofenceHardware.GEOFENCE_ERROR_ID_EXISTS;
1711 case GPS_GEOFENCE_ERROR_INVALID_TRANSITION:
1712 return GeofenceHardware.GEOFENCE_ERROR_INVALID_TRANSITION;
1713 case GPS_GEOFENCE_ERROR_TOO_MANY_GEOFENCES:
1714 return GeofenceHardware.GEOFENCE_ERROR_TOO_MANY_GEOFENCES;
1715 case GPS_GEOFENCE_ERROR_ID_UNKNOWN:
1716 return GeofenceHardware.GEOFENCE_ERROR_ID_UNKNOWN;
1717 default:
1718 return -1;
1719 }
1720 }
1721
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001722 @NativeEntryPoint
Wyatt Riley5d229832017-02-10 17:06:00 -08001723 private void reportGeofenceTransition(int geofenceId, Location location, int transition,
gomo48f1a642017-11-10 20:35:46 -08001724 long transitionTimestamp) {
Yu-Han Yang6dc9f052018-12-04 17:11:24 -08001725 mHandler.post(() -> {
1726 if (mGeofenceHardwareImpl == null) {
1727 mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
1728 }
Wyatt Riley5d229832017-02-10 17:06:00 -08001729
Yu-Han Yang6dc9f052018-12-04 17:11:24 -08001730 mGeofenceHardwareImpl.reportGeofenceTransition(
1731 geofenceId,
1732 location,
1733 transition,
1734 transitionTimestamp,
1735 GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE,
1736 FusedBatchOptions.SourceTechnologies.GNSS);
1737 });
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001738 }
1739
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001740 @NativeEntryPoint
Wyatt Riley5d229832017-02-10 17:06:00 -08001741 private void reportGeofenceStatus(int status, Location location) {
Yu-Han Yang6dc9f052018-12-04 17:11:24 -08001742 mHandler.post(() -> {
1743 if (mGeofenceHardwareImpl == null) {
1744 mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
1745 }
1746 int monitorStatus = GeofenceHardware.MONITOR_CURRENTLY_UNAVAILABLE;
1747 if (status == GPS_GEOFENCE_AVAILABLE) {
1748 monitorStatus = GeofenceHardware.MONITOR_CURRENTLY_AVAILABLE;
1749 }
1750 mGeofenceHardwareImpl.reportGeofenceMonitorStatus(
1751 GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE,
1752 monitorStatus,
1753 location,
1754 FusedBatchOptions.SourceTechnologies.GNSS);
1755 });
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001756 }
1757
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001758 @NativeEntryPoint
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001759 private void reportGeofenceAddStatus(int geofenceId, int status) {
Yu-Han Yang6dc9f052018-12-04 17:11:24 -08001760 mHandler.post(() -> {
1761 if (mGeofenceHardwareImpl == null) {
1762 mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
1763 }
1764 mGeofenceHardwareImpl.reportGeofenceAddStatus(geofenceId, getGeofenceStatus(status));
1765 });
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001766 }
1767
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001768 @NativeEntryPoint
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001769 private void reportGeofenceRemoveStatus(int geofenceId, int status) {
Yu-Han Yang6dc9f052018-12-04 17:11:24 -08001770 mHandler.post(() -> {
1771 if (mGeofenceHardwareImpl == null) {
1772 mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
1773 }
1774 mGeofenceHardwareImpl.reportGeofenceRemoveStatus(geofenceId, getGeofenceStatus(status));
1775 });
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001776 }
1777
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001778 @NativeEntryPoint
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001779 private void reportGeofencePauseStatus(int geofenceId, int status) {
Yu-Han Yang6dc9f052018-12-04 17:11:24 -08001780 mHandler.post(() -> {
1781 if (mGeofenceHardwareImpl == null) {
1782 mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
1783 }
1784 mGeofenceHardwareImpl.reportGeofencePauseStatus(geofenceId, getGeofenceStatus(status));
1785 });
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001786 }
1787
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001788 @NativeEntryPoint
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001789 private void reportGeofenceResumeStatus(int geofenceId, int status) {
Yu-Han Yang6dc9f052018-12-04 17:11:24 -08001790 mHandler.post(() -> {
1791 if (mGeofenceHardwareImpl == null) {
1792 mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
1793 }
1794 mGeofenceHardwareImpl.reportGeofenceResumeStatus(geofenceId, getGeofenceStatus(status));
1795 });
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001796 }
1797
Danke Xie22d1f9f2009-08-18 18:28:45 -04001798 //=============================================================
1799 // NI Client support
Miguel Torroja1e84da82010-07-27 07:02:24 +02001800 //=============================================================
Danke Xie22d1f9f2009-08-18 18:28:45 -04001801 private final INetInitiatedListener mNetInitiatedListener = new INetInitiatedListener.Stub() {
destradaaef752b62015-04-17 13:10:47 -07001802 // Sends a response for an NI request to HAL.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001803 @Override
gomo48f1a642017-11-10 20:35:46 -08001804 public boolean sendNiResponse(int notificationId, int userResponse) {
Miguel Torroja1e84da82010-07-27 07:02:24 +02001805 // TODO Add Permission check
Danke Xie22d1f9f2009-08-18 18:28:45 -04001806
gomo48f1a642017-11-10 20:35:46 -08001807 if (DEBUG) {
1808 Log.d(TAG, "sendNiResponse, notifId: " + notificationId +
1809 ", response: " + userResponse);
1810 }
Miguel Torroja1e84da82010-07-27 07:02:24 +02001811 native_send_ni_response(notificationId, userResponse);
Yu-Han Yang8a1b51d2018-12-26 22:18:31 -08001812
1813 StatsLog.write(StatsLog.GNSS_NI_EVENT_REPORTED,
1814 StatsLog.GNSS_NI_EVENT_REPORTED__EVENT_TYPE__NI_RESPONSE,
1815 notificationId,
1816 /* niType= */ 0,
1817 /* needNotify= */ false,
1818 /* needVerify= */ false,
1819 /* privacyOverride= */ false,
1820 /* timeout= */ 0,
1821 /* defaultResponse= */ 0,
1822 /* requestorId= */ null,
1823 /* text= */ null,
1824 /* requestorIdEncoding= */ 0,
1825 /* textEncoding= */ 0,
1826 mSuplEsEnabled,
Yu-Han Yang76f99952019-05-04 17:45:44 -07001827 isGpsEnabled(),
Yu-Han Yang8a1b51d2018-12-26 22:18:31 -08001828 userResponse);
1829
Miguel Torroja1e84da82010-07-27 07:02:24 +02001830 return true;
1831 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04001832 };
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001833
Danke Xie22d1f9f2009-08-18 18:28:45 -04001834 public INetInitiatedListener getNetInitiatedListener() {
1835 return mNetInitiatedListener;
1836 }
1837
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001838 /** Reports a NI notification. */
1839 @NativeEntryPoint
Miguel Torroja1e84da82010-07-27 07:02:24 +02001840 public void reportNiNotification(
1841 int notificationId,
1842 int niType,
1843 int notifyFlags,
1844 int timeout,
1845 int defaultResponse,
1846 String requestorId,
1847 String text,
1848 int requestorIdEncoding,
Hridya Valsaraju2ea29602016-09-13 08:38:09 -07001849 int textEncoding
gomo48f1a642017-11-10 20:35:46 -08001850 ) {
Miguel Torroja1e84da82010-07-27 07:02:24 +02001851 Log.i(TAG, "reportNiNotification: entered");
1852 Log.i(TAG, "notificationId: " + notificationId +
1853 ", niType: " + niType +
1854 ", notifyFlags: " + notifyFlags +
1855 ", timeout: " + timeout +
1856 ", defaultResponse: " + defaultResponse);
1857
1858 Log.i(TAG, "requestorId: " + requestorId +
1859 ", text: " + text +
1860 ", requestorIdEncoding: " + requestorIdEncoding +
1861 ", textEncoding: " + textEncoding);
1862
1863 GpsNiNotification notification = new GpsNiNotification();
1864
1865 notification.notificationId = notificationId;
1866 notification.niType = niType;
1867 notification.needNotify = (notifyFlags & GpsNetInitiatedHandler.GPS_NI_NEED_NOTIFY) != 0;
1868 notification.needVerify = (notifyFlags & GpsNetInitiatedHandler.GPS_NI_NEED_VERIFY) != 0;
gomo48f1a642017-11-10 20:35:46 -08001869 notification.privacyOverride =
1870 (notifyFlags & GpsNetInitiatedHandler.GPS_NI_PRIVACY_OVERRIDE) != 0;
Miguel Torroja1e84da82010-07-27 07:02:24 +02001871 notification.timeout = timeout;
1872 notification.defaultResponse = defaultResponse;
1873 notification.requestorId = requestorId;
1874 notification.text = text;
1875 notification.requestorIdEncoding = requestorIdEncoding;
1876 notification.textEncoding = textEncoding;
1877
Miguel Torroja1e84da82010-07-27 07:02:24 +02001878 mNIHandler.handleNiNotification(notification);
Yu-Han Yang8a1b51d2018-12-26 22:18:31 -08001879 StatsLog.write(StatsLog.GNSS_NI_EVENT_REPORTED,
1880 StatsLog.GNSS_NI_EVENT_REPORTED__EVENT_TYPE__NI_REQUEST,
1881 notification.notificationId,
1882 notification.niType,
1883 notification.needNotify,
1884 notification.needVerify,
1885 notification.privacyOverride,
1886 notification.timeout,
1887 notification.defaultResponse,
1888 notification.requestorId,
1889 notification.text,
1890 notification.requestorIdEncoding,
1891 notification.textEncoding,
1892 mSuplEsEnabled,
Yu-Han Yang76f99952019-05-04 17:45:44 -07001893 isGpsEnabled(),
Yu-Han Yang8a1b51d2018-12-26 22:18:31 -08001894 /* userResponse= */ 0);
Miguel Torroja1e84da82010-07-27 07:02:24 +02001895 }
1896
1897 /**
Miguel Torroja1e84da82010-07-27 07:02:24 +02001898 * We should be careful about receiving null string from the TelephonyManager,
1899 * because sending null String to JNI function would cause a crash.
1900 */
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001901 @NativeEntryPoint
Miguel Torroja1e84da82010-07-27 07:02:24 +02001902 private void requestSetID(int flags) {
1903 TelephonyManager phone = (TelephonyManager)
1904 mContext.getSystemService(Context.TELEPHONY_SERVICE);
destradaaef752b62015-04-17 13:10:47 -07001905 int type = AGPS_SETID_TYPE_NONE;
Anil Admale1539e82019-05-09 15:05:04 -07001906 String setId = null;
Miguel Torroja1e84da82010-07-27 07:02:24 +02001907
Anil Admale1539e82019-05-09 15:05:04 -07001908 int ddSubId = SubscriptionManager.getDefaultDataSubscriptionId();
Miguel Torroja1e84da82010-07-27 07:02:24 +02001909 if ((flags & AGPS_RIL_REQUEST_SETID_IMSI) == AGPS_RIL_REQUEST_SETID_IMSI) {
Anil Admale1539e82019-05-09 15:05:04 -07001910 if (SubscriptionManager.isValidSubscriptionId(ddSubId)) {
1911 setId = phone.getSubscriberId(ddSubId);
1912 }
1913 if (setId == null) {
1914 setId = phone.getSubscriberId();
1915 }
1916 if (setId != null) {
Miguel Torroja1e84da82010-07-27 07:02:24 +02001917 // This means the framework has the SIM card.
Miguel Torroja1e84da82010-07-27 07:02:24 +02001918 type = AGPS_SETID_TYPE_IMSI;
1919 }
gomo48f1a642017-11-10 20:35:46 -08001920 } else if ((flags & AGPS_RIL_REQUEST_SETID_MSISDN) == AGPS_RIL_REQUEST_SETID_MSISDN) {
Anil Admale1539e82019-05-09 15:05:04 -07001921 if (SubscriptionManager.isValidSubscriptionId(ddSubId)) {
1922 setId = phone.getLine1Number(ddSubId);
1923 }
1924 if (setId == null) {
1925 setId = phone.getLine1Number();
1926 }
1927 if (setId != null) {
Miguel Torroja1e84da82010-07-27 07:02:24 +02001928 // This means the framework has the SIM card.
Miguel Torroja1e84da82010-07-27 07:02:24 +02001929 type = AGPS_SETID_TYPE_MSISDN;
1930 }
1931 }
Anil Admale1539e82019-05-09 15:05:04 -07001932
1933 native_agps_set_id(type, (setId == null) ? "" : setId);
Miguel Torroja1e84da82010-07-27 07:02:24 +02001934 }
1935
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001936 @NativeEntryPoint
Yu-Han Yang53f4d6d2019-02-13 21:47:41 -08001937 private void requestLocation(boolean independentFromGnss, boolean isUserEmergency) {
Yu-Han Yange7baef32018-02-09 13:58:17 -08001938 if (DEBUG) {
Yu-Han Yang53f4d6d2019-02-13 21:47:41 -08001939 Log.d(TAG, "requestLocation. independentFromGnss: " + independentFromGnss
1940 + ", isUserEmergency: "
1941 + isUserEmergency);
Yu-Han Yange7baef32018-02-09 13:58:17 -08001942 }
Yu-Han Yang53f4d6d2019-02-13 21:47:41 -08001943 sendMessage(REQUEST_LOCATION, independentFromGnss ? 1 : 0, isUserEmergency);
Yu-Han Yange7baef32018-02-09 13:58:17 -08001944 }
1945
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001946 @NativeEntryPoint
Mike Lockwood9b9fb5c2011-06-29 15:09:40 -04001947 private void requestUtcTime() {
destradaae21252a2015-09-08 12:32:59 -07001948 if (DEBUG) Log.d(TAG, "utcTimeRequest");
Mike Lockwood9b9fb5c2011-06-29 15:09:40 -04001949 sendMessage(INJECT_NTP_TIME, 0, null);
1950 }
1951
Soonil Nagarkar1575a042018-10-24 17:54:54 -07001952 @NativeEntryPoint
Hridya Valsaraju2ea29602016-09-13 08:38:09 -07001953 private void requestRefLocation() {
Miguel Torroja1e84da82010-07-27 07:02:24 +02001954 TelephonyManager phone = (TelephonyManager)
1955 mContext.getSystemService(Context.TELEPHONY_SERVICE);
Victoria Leased50d0c32012-10-29 13:16:17 -07001956 final int phoneType = phone.getPhoneType();
1957 if (phoneType == TelephonyManager.PHONE_TYPE_GSM) {
Miguel Torroja1e84da82010-07-27 07:02:24 +02001958 GsmCellLocation gsm_cell = (GsmCellLocation) phone.getCellLocation();
Victoria Leased50d0c32012-10-29 13:16:17 -07001959 if ((gsm_cell != null) && (phone.getNetworkOperator() != null)
1960 && (phone.getNetworkOperator().length() > 3)) {
Miguel Torroja1e84da82010-07-27 07:02:24 +02001961 int type;
gomo48f1a642017-11-10 20:35:46 -08001962 int mcc = Integer.parseInt(phone.getNetworkOperator().substring(0, 3));
Miguel Torroja1e84da82010-07-27 07:02:24 +02001963 int mnc = Integer.parseInt(phone.getNetworkOperator().substring(3));
Mike Lockwoodedc0f3872010-10-22 09:16:17 -04001964 int networkType = phone.getNetworkType();
1965 if (networkType == TelephonyManager.NETWORK_TYPE_UMTS
gomo48f1a642017-11-10 20:35:46 -08001966 || networkType == TelephonyManager.NETWORK_TYPE_HSDPA
1967 || networkType == TelephonyManager.NETWORK_TYPE_HSUPA
1968 || networkType == TelephonyManager.NETWORK_TYPE_HSPA
1969 || networkType == TelephonyManager.NETWORK_TYPE_HSPAP) {
Miguel Torroja1e84da82010-07-27 07:02:24 +02001970 type = AGPS_REF_LOCATION_TYPE_UMTS_CELLID;
Mike Lockwoodedc0f3872010-10-22 09:16:17 -04001971 } else {
Miguel Torroja1e84da82010-07-27 07:02:24 +02001972 type = AGPS_REF_LOCATION_TYPE_GSM_CELLID;
Mike Lockwoodedc0f3872010-10-22 09:16:17 -04001973 }
Miguel Torroja1e84da82010-07-27 07:02:24 +02001974 native_agps_set_ref_location_cellid(type, mcc, mnc,
1975 gsm_cell.getLac(), gsm_cell.getCid());
Mike Lockwoodedc0f3872010-10-22 09:16:17 -04001976 } else {
gomo48f1a642017-11-10 20:35:46 -08001977 Log.e(TAG, "Error getting cell location info.");
Mike Lockwoodedc0f3872010-10-22 09:16:17 -04001978 }
Victoria Leased50d0c32012-10-29 13:16:17 -07001979 } else if (phoneType == TelephonyManager.PHONE_TYPE_CDMA) {
1980 Log.e(TAG, "CDMA not supported.");
Mike Lockwoodedc0f3872010-10-22 09:16:17 -04001981 }
Miguel Torroja1e84da82010-07-27 07:02:24 +02001982 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04001983
Anil Admal94ec76a2019-01-15 09:42:01 -08001984 // Implements method nfwNotifyCb() in IGnssVisibilityControlCallback.hal.
1985 @NativeEntryPoint
1986 private void reportNfwNotification(String proxyAppPackageName, byte protocolStack,
1987 String otherProtocolStackName, byte requestor, String requestorId, byte responseType,
1988 boolean inEmergencyMode, boolean isCachedLocation) {
1989 if (mGnssVisibilityControl == null) {
1990 Log.e(TAG, "reportNfwNotification: mGnssVisibilityControl is not initialized.");
1991 return;
1992 }
1993
1994 mGnssVisibilityControl.reportNfwNotification(proxyAppPackageName, protocolStack,
1995 otherProtocolStackName, requestor, requestorId, responseType, inEmergencyMode,
1996 isCachedLocation);
1997 }
1998
1999 // Implements method isInEmergencySession() in IGnssVisibilityControlCallback.hal.
2000 @NativeEntryPoint
2001 boolean isInEmergencySession() {
2002 return mNIHandler.getInEmergency();
2003 }
2004
Mike Lockwood98e48692010-04-07 16:32:51 -04002005 private void sendMessage(int message, int arg, Object obj) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002006 // hold a wake lock until this message is delivered
Jeff Brown028872f2012-08-25 13:07:01 -07002007 // note that this assumes the message will not be removed from the queue before
2008 // it is handled (otherwise the wake lock would be leaked).
Yu-Han Yang499a6ba2019-11-14 14:19:13 -08002009 mWakeLock.acquire(WAKELOCK_TIMEOUT_MILLIS);
Anil Admal4f97c942018-11-12 10:52:46 -08002010 if (DEBUG) {
2011 Log.d(TAG, "WakeLock acquired by sendMessage(" + messageIdAsString(message) + ", " + arg
Wyatt Rileycf879db2017-01-12 13:57:38 -08002012 + ", " + obj + ")");
2013 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002014 mHandler.obtainMessage(message, arg, 1, obj).sendToTarget();
Mike Lockwood98e48692010-04-07 16:32:51 -04002015 }
2016
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002017 private final class ProviderHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08002018 public ProviderHandler(Looper looper) {
2019 super(looper, null, true /*async*/);
Jeff Brown028872f2012-08-25 13:07:01 -07002020 }
2021
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002022 @Override
Mike Lockwood4a7b65e2010-10-25 16:35:55 -04002023 public void handleMessage(Message msg) {
Mike Lockwood98e48692010-04-07 16:32:51 -04002024 int message = msg.what;
2025 switch (message) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002026 case SET_REQUEST:
2027 GpsRequest gpsRequest = (GpsRequest) msg.obj;
2028 handleSetRequest(gpsRequest.request, gpsRequest.source);
Mike Lockwood03ca2162010-04-01 08:10:09 -07002029 break;
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002030 case INJECT_NTP_TIME:
Yu-Han Yanga1862b52018-02-20 17:05:59 -08002031 mNtpTimeHelper.retrieveAndInjectNtpTime();
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002032 break;
Yu-Han Yange7baef32018-02-09 13:58:17 -08002033 case REQUEST_LOCATION:
Yu-Han Yang53f4d6d2019-02-13 21:47:41 -08002034 handleRequestLocation(msg.arg1 == 1, (boolean) msg.obj);
Yu-Han Yange7baef32018-02-09 13:58:17 -08002035 break;
Kevin Tang8c6ac672019-03-22 12:31:01 -07002036 case DOWNLOAD_PSDS_DATA:
2037 handleDownloadPsdsData();
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002038 break;
Kevin Tang8c6ac672019-03-22 12:31:01 -07002039 case DOWNLOAD_PSDS_DATA_FINISHED:
2040 mDownloadPsdsDataPending = STATE_IDLE;
Kevin Tang40e1baf2012-01-10 14:32:44 -08002041 break;
destradaafb23c672015-04-16 14:01:27 -07002042 case INITIALIZE_HANDLER:
destradaae21252a2015-09-08 12:32:59 -07002043 handleInitialize();
destradaafb23c672015-04-16 14:01:27 -07002044 break;
Wyatt Riley26465d22018-02-12 13:44:24 -08002045 case REPORT_LOCATION:
2046 handleReportLocation(msg.arg1 == 1, (Location) msg.obj);
2047 break;
2048 case REPORT_SV_STATUS:
2049 handleReportSvStatus((SvStatusInfo) msg.obj);
2050 break;
Kweku Adams810c77d2019-08-28 07:45:00 -07002051 case UPDATE_LOW_POWER_MODE:
2052 updateLowPowerMode();
2053 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002055 if (msg.arg2 == 1) {
2056 // wakelock was taken for this message, release it
2057 mWakeLock.release();
Anil Admal4f97c942018-11-12 10:52:46 -08002058 if (DEBUG) {
2059 Log.d(TAG, "WakeLock released by handleMessage(" + messageIdAsString(message)
Wyatt Rileycf879db2017-01-12 13:57:38 -08002060 + ", " + msg.arg1 + ", " + msg.obj + ")");
2061 }
Mike Lockwood98e48692010-04-07 16:32:51 -04002062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 }
destradaafb23c672015-04-16 14:01:27 -07002064
2065 /**
Soonil Nagarkar1575a042018-10-24 17:54:54 -07002066 * This method is bound to {@link #GnssLocationProvider(Context, LocationProviderManager,
2067 * Looper)}.
destradaafb23c672015-04-16 14:01:27 -07002068 * It is in charge of loading properties and registering for events that will be posted to
2069 * this handler.
2070 */
destradaae21252a2015-09-08 12:32:59 -07002071 private void handleInitialize() {
Anil Admal0c2b21bd2019-05-03 18:29:02 -07002072 // class_init_native() already initializes the GNSS service handle during class loading.
2073 setupNativeGnssService(/* reinitializeGnssServiceHandle = */ false);
Wyatt Riley523a0cf2017-10-31 14:36:52 -07002074
Anil Admal94ec76a2019-01-15 09:42:01 -08002075 if (native_is_gnss_visibility_control_supported()) {
Anil Admal8a246a22019-05-05 00:34:55 -07002076 mGnssVisibilityControl = new GnssVisibilityControl(mContext, mLooper, mNIHandler);
Anil Admal94ec76a2019-01-15 09:42:01 -08002077 }
2078
destradaafb23c672015-04-16 14:01:27 -07002079 // load default GPS configuration
2080 // (this configuration might change in the future based on SIM changes)
Anil Admald71cf142018-12-21 14:59:36 -08002081 reloadGpsProperties();
destradaafb23c672015-04-16 14:01:27 -07002082
destradaafb23c672015-04-16 14:01:27 -07002083 // listen for events
WyattRiley6593cf12018-06-23 10:37:48 -07002084 IntentFilter intentFilter = new IntentFilter();
destradaafb23c672015-04-16 14:01:27 -07002085 intentFilter.addAction(ALARM_WAKEUP);
2086 intentFilter.addAction(ALARM_TIMEOUT);
destradaafb23c672015-04-16 14:01:27 -07002087 intentFilter.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
Adam Lesinski87c17df2015-05-27 13:24:13 -07002088 intentFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
destradaafb23c672015-04-16 14:01:27 -07002089 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
2090 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
Meng Wang19b214d2018-11-07 12:14:39 -08002091 intentFilter.addAction(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
Anil Admale1539e82019-05-09 15:05:04 -07002092 intentFilter.addAction(TelephonyIntents.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED);
destradaafb23c672015-04-16 14:01:27 -07002093 mContext.registerReceiver(mBroadcastReceiver, intentFilter, null, this);
2094
Anil Admal50ba15e2018-11-01 16:42:42 -07002095 mNetworkConnectivityHandler.registerNetworkCallbacks();
destradaae21252a2015-09-08 12:32:59 -07002096
destradaafb23c672015-04-16 14:01:27 -07002097 // listen for PASSIVE_PROVIDER updates
2098 LocationManager locManager =
2099 (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
2100 long minTime = 0;
2101 float minDistance = 0;
destradaafb23c672015-04-16 14:01:27 -07002102 LocationRequest request = LocationRequest.createFromDeprecatedProvider(
2103 LocationManager.PASSIVE_PROVIDER,
2104 minTime,
2105 minDistance,
Soonil Nagarkar1575a042018-10-24 17:54:54 -07002106 false);
destradaafb23c672015-04-16 14:01:27 -07002107 // Don't keep track of this request since it's done on behalf of other clients
2108 // (which are kept track of separately).
2109 request.setHideFromAppOps(true);
2110 locManager.requestLocationUpdates(
2111 request,
2112 new NetworkLocationListener(),
2113 getLooper());
Soonil Nagarkar1575a042018-10-24 17:54:54 -07002114
Soonil Nagarkar35c3b912019-01-31 10:31:24 -08002115 updateEnabled();
destradaafb23c672015-04-16 14:01:27 -07002116 }
2117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118
Yu-Han Yange7baef32018-02-09 13:58:17 -08002119 private abstract class LocationChangeListener implements LocationListener {
Soonil Nagarkar1575a042018-10-24 17:54:54 -07002120 private int mNumLocationUpdateRequest;
Yu-Han Yang07561382018-02-21 13:08:37 -08002121
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002122 @Override
gomo48f1a642017-11-10 20:35:46 -08002123 public void onStatusChanged(String provider, int status, Bundle extras) {
2124 }
2125
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002126 @Override
gomo48f1a642017-11-10 20:35:46 -08002127 public void onProviderEnabled(String provider) {
2128 }
2129
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002130 @Override
gomo48f1a642017-11-10 20:35:46 -08002131 public void onProviderDisabled(String provider) {
2132 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002133 }
2134
Yu-Han Yange7baef32018-02-09 13:58:17 -08002135 private final class NetworkLocationListener extends LocationChangeListener {
2136 @Override
2137 public void onLocationChanged(Location location) {
2138 // this callback happens on mHandler looper
2139 if (LocationManager.NETWORK_PROVIDER.equals(location.getProvider())) {
Anil Admal2ac70462019-06-28 19:17:41 -07002140 injectLocation(location);
Yu-Han Yange7baef32018-02-09 13:58:17 -08002141 }
2142 }
2143 }
2144
2145 private final class FusedLocationListener extends LocationChangeListener {
2146 @Override
2147 public void onLocationChanged(Location location) {
2148 if (LocationManager.FUSED_PROVIDER.equals(location.getProvider())) {
Yu-Han Yange7baef32018-02-09 13:58:17 -08002149 injectBestLocation(location);
2150 }
2151 }
2152 }
2153
Wyatt Rileycf879db2017-01-12 13:57:38 -08002154 /**
2155 * @return A string representing the given message ID.
2156 */
2157 private String messageIdAsString(int message) {
2158 switch (message) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002159 case SET_REQUEST:
2160 return "SET_REQUEST";
Wyatt Rileycf879db2017-01-12 13:57:38 -08002161 case INJECT_NTP_TIME:
2162 return "INJECT_NTP_TIME";
Yu-Han Yange7baef32018-02-09 13:58:17 -08002163 case REQUEST_LOCATION:
2164 return "REQUEST_LOCATION";
Kevin Tang8c6ac672019-03-22 12:31:01 -07002165 case DOWNLOAD_PSDS_DATA:
2166 return "DOWNLOAD_PSDS_DATA";
2167 case DOWNLOAD_PSDS_DATA_FINISHED:
2168 return "DOWNLOAD_PSDS_DATA_FINISHED";
Wyatt Rileycf879db2017-01-12 13:57:38 -08002169 case INITIALIZE_HANDLER:
2170 return "INITIALIZE_HANDLER";
Wyatt Riley26465d22018-02-12 13:44:24 -08002171 case REPORT_LOCATION:
2172 return "REPORT_LOCATION";
2173 case REPORT_SV_STATUS:
2174 return "REPORT_SV_STATUS";
Wyatt Rileycf879db2017-01-12 13:57:38 -08002175 default:
2176 return "<Unknown>";
2177 }
2178 }
2179
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002180 @Override
2181 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2182 StringBuilder s = new StringBuilder();
Soonil Nagarkar1c572552019-07-10 13:31:47 -07002183 s.append("mStarted=").append(mStarted).append(" (changed ");
WyattRileyba6072f2019-04-18 07:37:52 -07002184 TimeUtils.formatDuration(SystemClock.elapsedRealtime()
2185 - mStartedChangedElapsedRealtime, s);
2186 s.append(" ago)").append('\n');
Soonil Nagarkar1c572552019-07-10 13:31:47 -07002187 s.append("mFixInterval=").append(mFixInterval).append('\n');
2188 s.append("mLowPowerMode=").append(mLowPowerMode).append('\n');
2189 s.append("mGnssMeasurementsProvider.isRegistered()=")
Wyatt Riley74479bd2018-01-17 08:48:27 -08002190 .append(mGnssMeasurementsProvider.isRegistered()).append('\n');
Soonil Nagarkar1c572552019-07-10 13:31:47 -07002191 s.append("mGnssNavigationMessageProvider.isRegistered()=")
Wyatt Riley74479bd2018-01-17 08:48:27 -08002192 .append(mGnssNavigationMessageProvider.isRegistered()).append('\n');
Soonil Nagarkar1c572552019-07-10 13:31:47 -07002193 s.append("mDisableGpsForPowerManager=").append(mDisableGpsForPowerManager).append('\n');
2194 s.append("mTopHalCapabilities=0x").append(Integer.toHexString(mTopHalCapabilities));
destradaa25e8caf2015-08-24 14:14:44 -07002195 s.append(" ( ");
2196 if (hasCapability(GPS_CAPABILITY_SCHEDULING)) s.append("SCHEDULING ");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002197 if (hasCapability(GPS_CAPABILITY_MSB)) s.append("MSB ");
2198 if (hasCapability(GPS_CAPABILITY_MSA)) s.append("MSA ");
2199 if (hasCapability(GPS_CAPABILITY_SINGLE_SHOT)) s.append("SINGLE_SHOT ");
2200 if (hasCapability(GPS_CAPABILITY_ON_DEMAND_TIME)) s.append("ON_DEMAND_TIME ");
destradaa25e8caf2015-08-24 14:14:44 -07002201 if (hasCapability(GPS_CAPABILITY_GEOFENCING)) s.append("GEOFENCING ");
2202 if (hasCapability(GPS_CAPABILITY_MEASUREMENTS)) s.append("MEASUREMENTS ");
2203 if (hasCapability(GPS_CAPABILITY_NAV_MESSAGES)) s.append("NAV_MESSAGES ");
Anil Admalefd9dc62019-03-12 17:39:20 -07002204 if (hasCapability(GPS_CAPABILITY_LOW_POWER_MODE)) s.append("LOW_POWER_MODE ");
2205 if (hasCapability(GPS_CAPABILITY_SATELLITE_BLACKLIST)) s.append("SATELLITE_BLACKLIST ");
Anil Admal62c42dc2019-04-03 15:39:22 -07002206 if (hasCapability(GPS_CAPABILITY_MEASUREMENT_CORRECTIONS)) {
2207 s.append("MEASUREMENT_CORRECTIONS ");
2208 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002209 s.append(")\n");
Anil Admal3ba0fa92019-04-19 17:43:00 -07002210 if (hasCapability(GPS_CAPABILITY_MEASUREMENT_CORRECTIONS)) {
Soonil Nagarkar1c572552019-07-10 13:31:47 -07002211 s.append("SubHal=MEASUREMENT_CORRECTIONS[");
Anil Admalefd9dc62019-03-12 17:39:20 -07002212 s.append(mGnssMeasurementCorrectionsProvider.toStringCapabilities());
2213 s.append("]\n");
2214 }
Siddharth Raybb608c82017-03-16 11:33:34 -07002215 s.append(mGnssMetrics.dumpGnssMetricsAsText());
Soonil Nagarkar1c572552019-07-10 13:31:47 -07002216 s.append("native internal state: \n");
2217 s.append(" ").append(native_get_internal_state());
Wyatt Rileycf879db2017-01-12 13:57:38 -08002218 s.append("\n");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002219 pw.append(s);
2220 }
2221
Anil Admal0c2b21bd2019-05-03 18:29:02 -07002222 private void setupNativeGnssService(boolean reinitializeGnssServiceHandle) {
2223 native_init_once(reinitializeGnssServiceHandle);
Anil Admal7e3953b2019-05-04 20:45:22 -07002224
2225 /*
2226 * A cycle of native_init() and native_cleanup() is needed so that callbacks are
2227 * registered after bootup even when location is disabled.
2228 * This will allow Emergency SUPL to work even when location is disabled before device
2229 * restart.
2230 */
2231 boolean isInitialized = native_init();
2232 if (!isInitialized) {
2233 Log.w(TAG, "Native initialization failed.");
2234 } else {
2235 native_cleanup();
2236 }
2237 }
2238
Mike Lockwoodb16e7802009-08-06 09:26:02 -04002239 // preallocated to avoid memory allocation in reportNmea()
2240 private byte[] mNmeaBuffer = new byte[120];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 private static native void class_init_native();
gomo48f1a642017-11-10 20:35:46 -08002243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 private static native boolean native_is_supported();
gomo48f1a642017-11-10 20:35:46 -08002245
Anil Admal94ec76a2019-01-15 09:42:01 -08002246 private static native boolean native_is_gnss_visibility_control_supported();
2247
Anil Admal0c2b21bd2019-05-03 18:29:02 -07002248 private static native void native_init_once(boolean reinitializeGnssServiceHandle);
Yu-Han Yang6d317352018-03-15 11:53:01 -07002249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 private native boolean native_init();
gomo48f1a642017-11-10 20:35:46 -08002251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252 private native void native_cleanup();
gomo48f1a642017-11-10 20:35:46 -08002253
Mike Lockwood04598b62010-04-14 17:17:24 -04002254 private native boolean native_set_position_mode(int mode, int recurrence, int min_interval,
gomo48f1a642017-11-10 20:35:46 -08002255 int preferred_accuracy, int preferred_time, boolean lowPowerMode);
2256
Mike Lockwood04598b62010-04-14 17:17:24 -04002257 private native boolean native_start();
gomo48f1a642017-11-10 20:35:46 -08002258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002259 private native boolean native_stop();
gomo48f1a642017-11-10 20:35:46 -08002260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 private native void native_delete_aiding_data(int flags);
gomo48f1a642017-11-10 20:35:46 -08002262
Mike Lockwoodf602d362010-06-20 14:28:16 -07002263 private native int native_read_nmea(byte[] buffer, int bufferSize);
gomo48f1a642017-11-10 20:35:46 -08002264
Yu-Han Yange7baef32018-02-09 13:58:17 -08002265 private native void native_inject_best_location(
Pierre Fite-Georgelb50cdaf2019-02-25 15:42:45 -08002266 int gnssLocationFlags, double latitudeDegrees, double longitudeDegrees,
2267 double altitudeMeters, float speedMetersPerSec, float bearingDegrees,
2268 float horizontalAccuracyMeters, float verticalAccuracyMeters,
2269 float speedAccuracyMetersPerSecond, float bearingAccuracyDegrees,
Pierre Fite-Georgel9e96c572019-02-25 16:12:53 -08002270 long timestamp, int elapsedRealtimeFlags, long elapsedRealtimeNanos,
Yu-Han Yang3cd9a862019-03-25 17:00:03 -07002271 double elapsedRealtimeUncertaintyNanos);
Yu-Han Yange7baef32018-02-09 13:58:17 -08002272
Mike Lockwoodd26ce0d2009-06-11 12:25:46 -04002273 private native void native_inject_location(double latitude, double longitude, float accuracy);
2274
Kevin Tang8c6ac672019-03-22 12:31:01 -07002275 // PSDS Support
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 private native void native_inject_time(long time, long timeReference, int uncertainty);
gomo48f1a642017-11-10 20:35:46 -08002277
Kevin Tang8c6ac672019-03-22 12:31:01 -07002278 private native boolean native_supports_psds();
gomo48f1a642017-11-10 20:35:46 -08002279
Kevin Tang8c6ac672019-03-22 12:31:01 -07002280 private native void native_inject_psds_data(byte[] data, int length);
The Android Open Source Project10592532009-03-18 17:39:46 -07002281
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002282 // DEBUG Support
2283 private native String native_get_internal_state();
2284
2285 // AGPS Support
gomo48f1a642017-11-10 20:35:46 -08002286 private native void native_agps_ni_message(byte[] msg, int length);
2287
Mike Lockwooda9e54612009-06-19 14:54:42 -04002288 private native void native_set_agps_server(int type, String hostname, int port);
Danke Xie22d1f9f2009-08-18 18:28:45 -04002289
2290 // Network-initiated (NI) Support
2291 private native void native_send_ni_response(int notificationId, int userResponse);
Miguel Torroja1e84da82010-07-27 07:02:24 +02002292
Anil Admal50ba15e2018-11-01 16:42:42 -07002293 // AGPS ril support
Miguel Torroja1e84da82010-07-27 07:02:24 +02002294 private native void native_agps_set_ref_location_cellid(int type, int mcc, int mnc,
2295 int lac, int cid);
gomo48f1a642017-11-10 20:35:46 -08002296
Miguel Torroja1e84da82010-07-27 07:02:24 +02002297 private native void native_agps_set_id(int type, String setid);
Pierre Fite-Georgelb50cdaf2019-02-25 15:42:45 -08002298}