blob: cdf25cfe65f6ca4cfba0848aaf3f07ae573f1529 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.content.Context;
24import android.content.Intent;
The Android Open Source Project10592532009-03-18 17:39:46 -070025import android.content.IntentFilter;
Kevin Tanga5fe6b22011-06-05 14:25:16 -070026import android.database.Cursor;
destradaa0682809a2013-08-12 18:50:30 -070027import android.hardware.location.GeofenceHardware;
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -070028import android.hardware.location.GeofenceHardwareImpl;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.location.Criteria;
destradaa0682809a2013-08-12 18:50:30 -070030import android.location.FusedBatchOptions;
Lifu Tang30f95a72016-01-07 23:20:38 -080031import android.location.GnssStatus;
32import android.location.IGnssStatusListener;
33import android.location.IGnssStatusProvider;
Lifu Tang818aa2c2016-02-01 01:52:00 -080034import android.location.GnssMeasurementsEvent;
Lifu Tange8abe8e2016-04-01 10:32:05 -070035import android.location.GnssNavigationMessage;
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -070036import android.location.IGpsGeofenceHardware;
Mike Lockwood4e50b782009-04-03 08:24:43 -070037import android.location.ILocationManager;
Danke Xie22d1f9f2009-08-18 18:28:45 -040038import android.location.INetInitiatedListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.location.Location;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070040import android.location.LocationListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.location.LocationManager;
42import android.location.LocationProvider;
Stan Chesnutt1d72d8c2013-04-15 19:18:02 -070043import android.location.LocationRequest;
Mike Lockwood58bda982009-04-14 16:25:07 -040044import android.net.ConnectivityManager;
destradaae21252a2015-09-08 12:32:59 -070045import android.net.Network;
46import android.net.NetworkCapabilities;
Mike Lockwood03d24672009-10-08 15:45:03 -040047import android.net.NetworkInfo;
destradaae21252a2015-09-08 12:32:59 -070048import android.net.NetworkRequest;
Kevin Tanga5fe6b22011-06-05 14:25:16 -070049import android.net.Uri;
Kevin Tang40e1baf2012-01-10 14:32:44 -080050import android.os.AsyncTask;
jackqdyulei455e90a2017-02-09 15:29:16 -080051import android.os.PowerSaveState;
Dianne Hackborn91268cf2013-06-13 19:06:50 -070052import android.os.BatteryStats;
Mike Lockwood63aa5a62010-04-14 19:21:31 -040053import android.os.Binder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.Bundle;
Ecco Park4fa1ab72016-10-24 13:04:52 -070055import android.os.PersistableBundle;
Mike Lockwood62a8fc12010-03-22 14:23:26 -040056import android.os.Handler;
Victoria Lease5cd731a2012-12-19 15:04:21 -080057import android.os.Looper;
Mike Lockwood62a8fc12010-03-22 14:23:26 -040058import android.os.Message;
Mike Lockwood0528b9b2009-05-07 10:12:54 -040059import android.os.PowerManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.os.RemoteException;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -040061import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.os.SystemClock;
Colin Cross7c030ed2014-01-28 09:33:53 -080063import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070064import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070065import android.os.WorkSource;
Mike Lockwoodbcab8df2009-06-25 16:39:09 -040066import android.provider.Settings;
Kevin Tanga5fe6b22011-06-05 14:25:16 -070067import android.provider.Telephony.Carriers;
Miguel Torroja1e84da82010-07-27 07:02:24 +020068import android.provider.Telephony.Sms.Intents;
Wink Savillea374c3d2014-11-11 11:48:04 -080069import android.telephony.SubscriptionManager;
Wink Savilled09c4ca2014-11-22 10:08:16 -080070import android.telephony.SubscriptionManager.OnSubscriptionsChangedListener;
Miguel Torroja1e84da82010-07-27 07:02:24 +020071import android.telephony.TelephonyManager;
Ecco Park4fa1ab72016-10-24 13:04:52 -070072import android.telephony.CarrierConfigManager;
Miguel Torroja1e84da82010-07-27 07:02:24 +020073import android.telephony.gsm.GsmCellLocation;
Colin Cross7c030ed2014-01-28 09:33:53 -080074import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.util.Log;
Jeff Sharkey104344e2011-07-10 14:20:41 -070076import android.util.NtpTrustedTime;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080077
jackqdyulei455e90a2017-02-09 15:29:16 -080078import com.android.internal.app.IAppOpsService;
79import com.android.internal.app.IBatteryStats;
Siddharth Raybb608c82017-03-16 11:33:34 -070080import com.android.internal.location.gnssmetrics.GnssMetrics;
jackqdyulei455e90a2017-02-09 15:29:16 -080081import com.android.internal.location.GpsNetInitiatedHandler;
82import com.android.internal.location.GpsNetInitiatedHandler.GpsNiNotification;
83import com.android.internal.location.ProviderProperties;
84import com.android.internal.location.ProviderRequest;
Siddharth Raybb608c82017-03-16 11:33:34 -070085
jackqdyulei455e90a2017-02-09 15:29:16 -080086import com.android.server.power.BatterySaverPolicy;
87import com.android.server.power.BatterySaverPolicy.ServiceType;
88
89import libcore.io.IoUtils;
90
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import java.io.File;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070092import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import java.io.FileInputStream;
94import java.io.IOException;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070095import java.io.PrintWriter;
destradaaea8a8a62014-06-23 18:19:03 -070096import java.net.InetAddress;
97import java.net.UnknownHostException;
Wyatt Rileycf879db2017-01-12 13:57:38 -080098import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080099import java.util.Arrays;
Mike Lockwoodf1218be2010-01-29 09:20:06 -0500100import java.util.Date;
Wyatt Rileycf879db2017-01-12 13:57:38 -0800101import java.util.List;
Danke Xie22d1f9f2009-08-18 18:28:45 -0400102import java.util.Map.Entry;
Jake Hambyb49a73d2011-03-15 20:09:46 -0700103import java.util.Properties;
Hridya Valsaraju2ea29602016-09-13 08:38:09 -0700104import java.util.Map;
105import java.util.HashMap;
Colin Cross7c030ed2014-01-28 09:33:53 -0800106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107/**
gomo4402af62017-01-11 13:20:13 -0800108 * A GNSS implementation of LocationProvider used by LocationManager.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 *
110 * {@hide}
111 */
Lifu Tang30f95a72016-01-07 23:20:38 -0800112public class GnssLocationProvider implements LocationProviderInterface {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113
Lifu Tang30f95a72016-01-07 23:20:38 -0800114 private static final String TAG = "GnssLocationProvider";
Mike Lockwood29c84342009-05-06 14:01:15 -0400115
Brian Muramatsu1715cb32012-08-08 17:32:21 -0700116 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
117 private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400118
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700119 private static final ProviderProperties PROPERTIES = new ProviderProperties(
120 true, true, false, false, true, true, true,
121 Criteria.POWER_HIGH, Criteria.ACCURACY_FINE);
122
gomo4402af62017-01-11 13:20:13 -0800123 // these need to match GnssPositionMode enum in IGnss.hal
The Android Open Source Project10592532009-03-18 17:39:46 -0700124 private static final int GPS_POSITION_MODE_STANDALONE = 0;
125 private static final int GPS_POSITION_MODE_MS_BASED = 1;
126 private static final int GPS_POSITION_MODE_MS_ASSISTED = 2;
127
gomo4402af62017-01-11 13:20:13 -0800128 // these need to match GnssPositionRecurrence enum in IGnss.hal
Mike Lockwood04598b62010-04-14 17:17:24 -0400129 private static final int GPS_POSITION_RECURRENCE_PERIODIC = 0;
130 private static final int GPS_POSITION_RECURRENCE_SINGLE = 1;
131
gomo4402af62017-01-11 13:20:13 -0800132 // these need to match GnssStatusValue enum in IGnssCallback.hal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 private static final int GPS_STATUS_NONE = 0;
134 private static final int GPS_STATUS_SESSION_BEGIN = 1;
135 private static final int GPS_STATUS_SESSION_END = 2;
136 private static final int GPS_STATUS_ENGINE_ON = 3;
137 private static final int GPS_STATUS_ENGINE_OFF = 4;
138
gomo4402af62017-01-11 13:20:13 -0800139 // these need to match AGnssStatusValue enum in IAGnssCallback.hal
Mike Lockwoode3635c92009-05-11 08:38:02 -0400140 /** AGPS status event values. */
141 private static final int GPS_REQUEST_AGPS_DATA_CONN = 1;
142 private static final int GPS_RELEASE_AGPS_DATA_CONN = 2;
143 private static final int GPS_AGPS_DATA_CONNECTED = 3;
144 private static final int GPS_AGPS_DATA_CONN_DONE = 4;
145 private static final int GPS_AGPS_DATA_CONN_FAILED = 5;
Mike Lockwood58bda982009-04-14 16:25:07 -0400146
gomo4402af62017-01-11 13:20:13 -0800147 // these need to match GnssLocationFlags enum in types.hal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 private static final int LOCATION_INVALID = 0;
149 private static final int LOCATION_HAS_LAT_LONG = 1;
150 private static final int LOCATION_HAS_ALTITUDE = 2;
151 private static final int LOCATION_HAS_SPEED = 4;
152 private static final int LOCATION_HAS_BEARING = 8;
gomo4402af62017-01-11 13:20:13 -0800153 private static final int LOCATION_HAS_HORIZONTAL_ACCURACY = 16;
154 private static final int LOCATION_HAS_VERTICAL_ACCURACY = 32;
155 private static final int LOCATION_HAS_SPEED_ACCURACY = 64;
156 private static final int LOCATION_HAS_BEARING_ACCURACY = 128;
Mike Lockwoode3635c92009-05-11 08:38:02 -0400157
gomo4402af62017-01-11 13:20:13 -0800158
159 // IMPORTANT - the GPS_DELETE_* symbols here must match GnssAidingData enum in IGnss.hal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private static final int GPS_DELETE_EPHEMERIS = 0x0001;
161 private static final int GPS_DELETE_ALMANAC = 0x0002;
162 private static final int GPS_DELETE_POSITION = 0x0004;
163 private static final int GPS_DELETE_TIME = 0x0008;
164 private static final int GPS_DELETE_IONO = 0x0010;
165 private static final int GPS_DELETE_UTC = 0x0020;
166 private static final int GPS_DELETE_HEALTH = 0x0040;
167 private static final int GPS_DELETE_SVDIR = 0x0080;
168 private static final int GPS_DELETE_SVSTEER = 0x0100;
169 private static final int GPS_DELETE_SADATA = 0x0200;
170 private static final int GPS_DELETE_RTI = 0x0400;
171 private static final int GPS_DELETE_CELLDB_INFO = 0x8000;
172 private static final int GPS_DELETE_ALL = 0xFFFF;
173
gomo4402af62017-01-11 13:20:13 -0800174 // The GPS_CAPABILITY_* flags must match Capabilities enum in IGnssCallback.hal
Mike Lockwood04598b62010-04-14 17:17:24 -0400175 private static final int GPS_CAPABILITY_SCHEDULING = 0x0000001;
176 private static final int GPS_CAPABILITY_MSB = 0x0000002;
177 private static final int GPS_CAPABILITY_MSA = 0x0000004;
178 private static final int GPS_CAPABILITY_SINGLE_SHOT = 0x0000008;
Mike Lockwood9b9fb5c2011-06-29 15:09:40 -0400179 private static final int GPS_CAPABILITY_ON_DEMAND_TIME = 0x0000010;
destradaa6568d702014-10-27 12:47:41 -0700180 private static final int GPS_CAPABILITY_GEOFENCING = 0x0000020;
181 private static final int GPS_CAPABILITY_MEASUREMENTS = 0x0000040;
182 private static final int GPS_CAPABILITY_NAV_MESSAGES = 0x0000080;
Mike Lockwood04598b62010-04-14 17:17:24 -0400183
Tsuwei Chen462bcd82014-09-17 12:28:49 -0700184 // The AGPS SUPL mode
185 private static final int AGPS_SUPL_MODE_MSA = 0x02;
186 private static final int AGPS_SUPL_MODE_MSB = 0x01;
187
gomo4402af62017-01-11 13:20:13 -0800188 // these need to match AGnssType enum in IAGnssCallback.hal
Mike Lockwoode3635c92009-05-11 08:38:02 -0400189 private static final int AGPS_TYPE_SUPL = 1;
190 private static final int AGPS_TYPE_C2K = 2;
191
gomo4402af62017-01-11 13:20:13 -0800192 // these must match the ApnIpType enum in IAGnss.hal
destradaa96a14702014-06-05 11:36:30 -0700193 private static final int APN_INVALID = 0;
194 private static final int APN_IPV4 = 1;
195 private static final int APN_IPV6 = 2;
196 private static final int APN_IPV4V6 = 3;
197
Mike Lockwoode3635c92009-05-11 08:38:02 -0400198 // for mAGpsDataConnectionState
199 private static final int AGPS_DATA_CONNECTION_CLOSED = 0;
200 private static final int AGPS_DATA_CONNECTION_OPENING = 1;
201 private static final int AGPS_DATA_CONNECTION_OPEN = 2;
Mike Lockwood58bda982009-04-14 16:25:07 -0400202
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400203 // Handler messages
204 private static final int CHECK_LOCATION = 1;
205 private static final int ENABLE = 2;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700206 private static final int SET_REQUEST = 3;
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400207 private static final int UPDATE_NETWORK_STATE = 4;
208 private static final int INJECT_NTP_TIME = 5;
209 private static final int DOWNLOAD_XTRA_DATA = 6;
210 private static final int UPDATE_LOCATION = 7;
211 private static final int ADD_LISTENER = 8;
212 private static final int REMOVE_LISTENER = 9;
Kevin Tang40e1baf2012-01-10 14:32:44 -0800213 private static final int INJECT_NTP_TIME_FINISHED = 10;
214 private static final int DOWNLOAD_XTRA_DATA_FINISHED = 11;
destradaafb23c672015-04-16 14:01:27 -0700215 private static final int SUBSCRIPTION_OR_SIM_CHANGED = 12;
216 private static final int INITIALIZE_HANDLER = 13;
destradaae21252a2015-09-08 12:32:59 -0700217 private static final int REQUEST_SUPL_CONNECTION = 14;
218 private static final int RELEASE_SUPL_CONNECTION = 15;
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400219
Miguel Torroja1e84da82010-07-27 07:02:24 +0200220 // Request setid
221 private static final int AGPS_RIL_REQUEST_SETID_IMSI = 1;
222 private static final int AGPS_RIL_REQUEST_SETID_MSISDN = 2;
223
Hridya Valsaraju2ea29602016-09-13 08:38:09 -0700224 //TODO(b/33112647): Create gps_debug.conf with commented career parameters.
225 private static final String DEBUG_PROPERTIES_FILE = "/etc/gps_debug.conf";
Miguel Torroja1e84da82010-07-27 07:02:24 +0200226
227 // ref. location info
228 private static final int AGPS_REF_LOCATION_TYPE_GSM_CELLID = 1;
229 private static final int AGPS_REF_LOCATION_TYPE_UMTS_CELLID = 2;
Miguel Torroja1e84da82010-07-27 07:02:24 +0200230
231 // set id info
232 private static final int AGPS_SETID_TYPE_NONE = 0;
233 private static final int AGPS_SETID_TYPE_IMSI = 1;
234 private static final int AGPS_SETID_TYPE_MSISDN = 2;
235
destradaa0682809a2013-08-12 18:50:30 -0700236 private static final int GPS_GEOFENCE_UNAVAILABLE = 1<<0L;
237 private static final int GPS_GEOFENCE_AVAILABLE = 1<<1L;
238
gomo4402af62017-01-11 13:20:13 -0800239 // GPS Geofence errors. Should match GeofenceStatus enum in IGnssGeofenceCallback.hal.
destradaa0682809a2013-08-12 18:50:30 -0700240 private static final int GPS_GEOFENCE_OPERATION_SUCCESS = 0;
241 private static final int GPS_GEOFENCE_ERROR_TOO_MANY_GEOFENCES = 100;
242 private static final int GPS_GEOFENCE_ERROR_ID_EXISTS = -101;
243 private static final int GPS_GEOFENCE_ERROR_ID_UNKNOWN = -102;
244 private static final int GPS_GEOFENCE_ERROR_INVALID_TRANSITION = -103;
245 private static final int GPS_GEOFENCE_ERROR_GENERIC = -149;
246
Tsuwei Chen678c13c2014-09-22 17:48:41 -0700247 // TCP/IP constants.
248 // Valid TCP/UDP port range is (0, 65535].
249 private static final int TCP_MIN_PORT = 0;
250 private static final int TCP_MAX_PORT = 0xffff;
251
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700252 /** simpler wrapper for ProviderRequest + Worksource */
253 private static class GpsRequest {
254 public ProviderRequest request;
255 public WorkSource source;
256 public GpsRequest(ProviderRequest request, WorkSource source) {
257 this.request = request;
258 this.source = source;
259 }
260 }
261
262 private Object mLock = new Object();
263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 // current status
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400265 private int mStatus = LocationProvider.TEMPORARILY_UNAVAILABLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266
267 // time for last status update
268 private long mStatusUpdateTime = SystemClock.elapsedRealtime();
Mike Lockwoodd53ba012010-04-15 20:41:26 -0400269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 // turn off GPS fix icon if we haven't received a fix in 10 seconds
Mike Lockwood04598b62010-04-14 17:17:24 -0400271 private static final long RECENT_FIX_TIMEOUT = 10 * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272
Mike Lockwood0632ca72009-05-14 15:51:03 -0400273 // stop trying if we do not receive a fix within 60 seconds
Mike Lockwood04598b62010-04-14 17:17:24 -0400274 private static final int NO_FIX_TIMEOUT = 60 * 1000;
Mike Lockwood0632ca72009-05-14 15:51:03 -0400275
Nick Pellyb041f232012-05-07 17:12:25 -0700276 // if the fix interval is below this we leave GPS on,
277 // if above then we cycle the GPS driver.
278 // Typical hot TTTF is ~5 seconds, so 10 seconds seems sane.
279 private static final int GPS_POLLING_THRESHOLD_INTERVAL = 10 * 1000;
280
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700281 // how often to request NTP time, in milliseconds
282 // current setting 24 hours
283 private static final long NTP_INTERVAL = 24*60*60*1000;
284 // how long to wait if we have a network error in NTP or XTRA downloading
Wei Liu6f6326b2015-06-24 23:47:50 -0700285 // the initial value of the exponential backoff
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700286 // current setting - 5 minutes
287 private static final long RETRY_INTERVAL = 5*60*1000;
Wei Liu6f6326b2015-06-24 23:47:50 -0700288 // how long to wait if we have a network error in NTP or XTRA downloading
289 // the max value of the exponential backoff
290 // current setting - 4 hours
291 private static final long MAX_RETRY_INTERVAL = 4*60*60*1000;
292
Wei Wangc5706f62017-04-18 11:26:26 -0700293 // Timeout when holding wakelocks for downloading XTRA data.
294 private static final long DOWNLOAD_XTRA_DATA_TIMEOUT_MS = 60 * 1000;
295
Wei Liu6f6326b2015-06-24 23:47:50 -0700296 private BackOff mNtpBackOff = new BackOff(RETRY_INTERVAL, MAX_RETRY_INTERVAL);
297 private BackOff mXtraBackOff = new BackOff(RETRY_INTERVAL, MAX_RETRY_INTERVAL);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700298
299 // true if we are enabled, protected by this
300 private boolean mEnabled;
301
Kevin Tang40e1baf2012-01-10 14:32:44 -0800302 // states for injecting ntp and downloading xtra data
303 private static final int STATE_PENDING_NETWORK = 0;
304 private static final int STATE_DOWNLOADING = 1;
305 private static final int STATE_IDLE = 2;
306
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400307 // flags to trigger NTP or XTRA data download when network becomes available
308 // initialized to true so we do NTP and XTRA when the network comes up after booting
Kevin Tang40e1baf2012-01-10 14:32:44 -0800309 private int mInjectNtpTimePending = STATE_PENDING_NETWORK;
310 private int mDownloadXtraDataPending = STATE_PENDING_NETWORK;
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400311
destradaa56b47f82015-07-24 10:56:18 -0700312 // set to true if the GPS engine requested on-demand NTP time requests
313 private boolean mOnDemandTimeInjection;
Mike Lockwood9b9fb5c2011-06-29 15:09:40 -0400314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 // true if GPS is navigating
316 private boolean mNavigating;
Mike Lockwoodcf1d8cb2010-01-20 10:14:54 -0500317
318 // true if GPS engine is on
319 private boolean mEngineOn;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700320
Mike Lockwood04598b62010-04-14 17:17:24 -0400321 // requested frequency of fixes, in milliseconds
322 private int mFixInterval = 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323
324 // true if we started navigation
325 private boolean mStarted;
326
Stan Chesnutt1d72d8c2013-04-15 19:18:02 -0700327 // true if single shot request is in progress
328 private boolean mSingleShot;
329
Mike Lockwood04598b62010-04-14 17:17:24 -0400330 // capabilities of the GPS engine
331 private int mEngineCapabilities;
332
Mike Lockwood1a1cd3a2010-08-17 07:42:54 -0400333 // true if XTRA is supported
334 private boolean mSupportsXtra;
335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 // for calculating time to first fix
337 private long mFixRequestTime = 0;
338 // time to first fix for most recent session
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700339 private int mTimeToFirstFix = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 // time we received our last fix
341 private long mLastFixTime;
342
Mike Lockwood04598b62010-04-14 17:17:24 -0400343 private int mPositionMode;
344
David Christied4edf4c2014-08-12 15:22:27 -0700345 // Current request from underlying location clients.
346 private ProviderRequest mProviderRequest = null;
347 // Current list of underlying location clients.
348 private WorkSource mWorkSource = null;
349 // True if gps should be disabled (used to support battery saver mode in settings).
350 private boolean mDisableGps = false;
351
destradaafb23c672015-04-16 14:01:27 -0700352 /**
353 * Properties loaded from PROPERTIES_FILE.
354 * It must be accessed only inside {@link #mHandler}.
355 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 private Properties mProperties;
destradaafb23c672015-04-16 14:01:27 -0700357
Mike Lockwood734d6032009-07-28 18:30:25 -0700358 private String mSuplServerHost;
Tsuwei Chen678c13c2014-09-22 17:48:41 -0700359 private int mSuplServerPort = TCP_MIN_PORT;
Mike Lockwood734d6032009-07-28 18:30:25 -0700360 private String mC2KServerHost;
361 private int mC2KServerPort;
Tsuwei Chen3324e952014-09-07 01:30:42 -0700362 private boolean mSuplEsEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400364 private final Context mContext;
Jeff Sharkey104344e2011-07-10 14:20:41 -0700365 private final NtpTrustedTime mNtpTime;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700366 private final ILocationManager mILocationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 private Location mLocation = new Location(LocationManager.GPS_PROVIDER);
368 private Bundle mLocationExtras = new Bundle();
Lifu Tang30f95a72016-01-07 23:20:38 -0800369 private final GnssStatusListenerHelper mListenerHelper;
Lifu Tang818aa2c2016-02-01 01:52:00 -0800370 private final GnssMeasurementsProvider mGnssMeasurementsProvider;
371 private final GnssNavigationMessageProvider mGnssNavigationMessageProvider;
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400372
Victoria Lease5c24fd02012-10-01 11:00:50 -0700373 // Handler for processing events
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400374 private Handler mHandler;
The Android Open Source Project10592532009-03-18 17:39:46 -0700375
destradaae21252a2015-09-08 12:32:59 -0700376 /** It must be accessed only inside {@link #mHandler}. */
Mike Lockwoode3635c92009-05-11 08:38:02 -0400377 private int mAGpsDataConnectionState;
destradaae21252a2015-09-08 12:32:59 -0700378 /** It must be accessed only inside {@link #mHandler}. */
destradaa96a14702014-06-05 11:36:30 -0700379 private InetAddress mAGpsDataConnectionIpAddr;
destradaae21252a2015-09-08 12:32:59 -0700380
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400381 private final ConnectivityManager mConnMgr;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700382 private final GpsNetInitiatedHandler mNIHandler;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400383
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400384 // Wakelocks
Lifu Tang30f95a72016-01-07 23:20:38 -0800385 private final static String WAKELOCK_KEY = "GnssLocationProvider";
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400386 private final PowerManager.WakeLock mWakeLock;
Wei Wangb71c0492017-05-01 20:24:19 -0700387 private static final String DOWNLOAD_EXTRA_WAKELOCK_KEY = "GnssLocationProviderXtraDownload";
388 private final PowerManager.WakeLock mDownloadXtraWakeLock;
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400389
Mike Lockwood29c84342009-05-06 14:01:15 -0400390 // Alarms
391 private final static String ALARM_WAKEUP = "com.android.internal.location.ALARM_WAKEUP";
Mike Lockwood0632ca72009-05-14 15:51:03 -0400392 private final static String ALARM_TIMEOUT = "com.android.internal.location.ALARM_TIMEOUT";
Tsuwei Chen52617bb2014-08-25 11:49:11 -0700393
394 // SIM/Carrier info.
395 private final static String SIM_STATE_CHANGED = "android.intent.action.SIM_STATE_CHANGED";
396
Ecco Park624ac3c2016-07-18 14:08:05 -0700397 // Persist property for LPP_PROFILE
398 private final static String LPP_PROFILE = "persist.sys.gps.lpp";
399
Ecco Park624ac3c2016-07-18 14:08:05 -0700400
401
David Christied4edf4c2014-08-12 15:22:27 -0700402 private final PowerManager mPowerManager;
Mike Lockwood29c84342009-05-06 14:01:15 -0400403 private final AlarmManager mAlarmManager;
404 private final PendingIntent mWakeupIntent;
Mike Lockwood0632ca72009-05-14 15:51:03 -0400405 private final PendingIntent mTimeoutIntent;
Mike Lockwood29c84342009-05-06 14:01:15 -0400406
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800407 private final IAppOpsService mAppOpsService;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400408 private final IBatteryStats mBatteryStats;
The Android Open Source Project10592532009-03-18 17:39:46 -0700409
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700410 // only modified on handler thread
Dianne Hackborn002a54e2013-01-10 17:34:55 -0800411 private WorkSource mClientSource = new WorkSource();
Mike Lockwoodf1218be2010-01-29 09:20:06 -0500412
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700413 private GeofenceHardwareImpl mGeofenceHardwareImpl;
Lifu Tang82f893d2016-01-21 18:15:33 -0800414 private int mYearOfHardware = 0;
415
Wyatt Riley5d5bac82016-11-01 07:05:16 -0700416 // Set lower than the current ITAR limit of 600m/s to allow this to trigger even if GPS HAL
417 // stops output right at 600m/s, depriving this of the information of a device that reaches
418 // greater than 600m/s, and higher than the speed of sound to avoid impacting most use cases.
419 private static final float ITAR_SPEED_LIMIT_METERS_PER_SECOND = 400.0F;
420 private boolean mItarSpeedLimitExceeded = false;
421
Siddharth Raybb608c82017-03-16 11:33:34 -0700422 // GNSS Metrics
423 private GnssMetrics mGnssMetrics;
424
Lifu Tang30f95a72016-01-07 23:20:38 -0800425 private final IGnssStatusProvider mGnssStatusProvider = new IGnssStatusProvider.Stub() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700426 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -0800427 public void registerGnssStatusCallback(IGnssStatusListener callback) {
428 mListenerHelper.addListener(callback);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400429 }
430
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700431 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -0800432 public void unregisterGnssStatusCallback(IGnssStatusListener callback) {
433 mListenerHelper.removeListener(callback);
destradaaea8a8a62014-06-23 18:19:03 -0700434 }
435 };
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400436
Lifu Tang30f95a72016-01-07 23:20:38 -0800437 public IGnssStatusProvider getGnssStatusProvider() {
438 return mGnssStatusProvider;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400439 }
440
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700441 public IGpsGeofenceHardware getGpsGeofenceProxy() {
442 return mGpsGeofenceBinder;
443 }
444
Lifu Tang818aa2c2016-02-01 01:52:00 -0800445 public GnssMeasurementsProvider getGnssMeasurementsProvider() {
446 return mGnssMeasurementsProvider;
destradaaea8a8a62014-06-23 18:19:03 -0700447 }
448
Lifu Tang818aa2c2016-02-01 01:52:00 -0800449 public GnssNavigationMessageProvider getGnssNavigationMessageProvider() {
450 return mGnssNavigationMessageProvider;
destradaa4b3e3932014-07-21 18:01:47 -0700451 }
452
destradaae21252a2015-09-08 12:32:59 -0700453 /**
454 * Callback used to listen for data connectivity changes.
455 */
456 private final ConnectivityManager.NetworkCallback mNetworkConnectivityCallback =
457 new ConnectivityManager.NetworkCallback() {
458 @Override
459 public void onAvailable(Network network) {
Wyatt Riley0d6e54e22016-10-05 12:03:03 -0700460 if (mInjectNtpTimePending == STATE_PENDING_NETWORK) {
461 requestUtcTime();
462 }
463 if (mDownloadXtraDataPending == STATE_PENDING_NETWORK) {
464 xtraDownloadRequest();
465 }
Wyatt Riley41f6bce2016-12-13 10:45:29 -0800466 // Always on, notify HAL so it can get data it needs
Wyatt Rileybb9c9902016-12-07 07:16:25 -0800467 sendMessage(UPDATE_NETWORK_STATE, 0 /*arg*/, network);
destradaae21252a2015-09-08 12:32:59 -0700468 }
Kevin Tang71ad5fe2017-05-10 19:36:20 -0700469
470 @Override
471 public void onLost(Network network) {
472 sendMessage(UPDATE_NETWORK_STATE, 0 /*arg*/, network);
473 }
destradaae21252a2015-09-08 12:32:59 -0700474 };
475
476 /**
477 * Callback used to listen for availability of a requested SUPL connection.
478 * It is kept as a separate instance from {@link #mNetworkConnectivityCallback} to be able to
479 * manage the registration/un-registration lifetimes separate.
480 */
481 private final ConnectivityManager.NetworkCallback mSuplConnectivityCallback =
482 new ConnectivityManager.NetworkCallback() {
483 @Override
Wyatt Riley41f6bce2016-12-13 10:45:29 -0800484 public void onAvailable(Network network) {
485 // Specific to a change to a SUPL enabled network becoming ready
486 sendMessage(UPDATE_NETWORK_STATE, 0 /*arg*/, network);
487 }
488
489 @Override
destradaae21252a2015-09-08 12:32:59 -0700490 public void onLost(Network network) {
491 releaseSuplConnection(GPS_RELEASE_AGPS_DATA_CONN);
492 }
destradaae21252a2015-09-08 12:32:59 -0700493 };
494
Tsuwei Chen52617bb2014-08-25 11:49:11 -0700495 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
The Android Open Source Project10592532009-03-18 17:39:46 -0700496 @Override public void onReceive(Context context, Intent intent) {
497 String action = intent.getAction();
Tsuwei Chen48d37f92014-09-05 15:15:34 -0700498 if (DEBUG) Log.d(TAG, "receive broadcast intent, action: " + action);
destradaaee9fd342015-08-31 13:31:17 -0700499 if (action == null) {
500 return;
501 }
502
Mike Lockwood29c84342009-05-06 14:01:15 -0400503 if (action.equals(ALARM_WAKEUP)) {
Stan Chesnutt1d72d8c2013-04-15 19:18:02 -0700504 startNavigating(false);
Mike Lockwood0632ca72009-05-14 15:51:03 -0400505 } else if (action.equals(ALARM_TIMEOUT)) {
Mike Lockwood0632ca72009-05-14 15:51:03 -0400506 hibernate();
David Christied4edf4c2014-08-12 15:22:27 -0700507 } else if (PowerManager.ACTION_POWER_SAVE_MODE_CHANGED.equals(action)
Adam Lesinski87c17df2015-05-27 13:24:13 -0700508 || PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(action)
David Christied4edf4c2014-08-12 15:22:27 -0700509 || Intent.ACTION_SCREEN_OFF.equals(action)
510 || Intent.ACTION_SCREEN_ON.equals(action)) {
511 updateLowPowerMode();
Wink Savillea374c3d2014-11-11 11:48:04 -0800512 } else if (action.equals(SIM_STATE_CHANGED)) {
513 subscriptionOrSimChanged(context);
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
Wink Savilled09c4ca2014-11-22 10:08:16 -0800518 private final OnSubscriptionsChangedListener mOnSubscriptionsChangedListener =
519 new OnSubscriptionsChangedListener() {
Wink Savillea374c3d2014-11-11 11:48:04 -0800520 @Override
Wink Savilled09c4ca2014-11-22 10:08:16 -0800521 public void onSubscriptionsChanged() {
destradaafb23c672015-04-16 14:01:27 -0700522 sendMessage(SUBSCRIPTION_OR_SIM_CHANGED, 0, null);
Wink Savillea374c3d2014-11-11 11:48:04 -0800523 }
524 };
525
526 private void subscriptionOrSimChanged(Context context) {
Joe Onorato0c484102016-02-01 18:04:24 -0800527 if (DEBUG) Log.d(TAG, "received SIM related action: ");
Wink Savillea374c3d2014-11-11 11:48:04 -0800528 TelephonyManager phone = (TelephonyManager)
529 mContext.getSystemService(Context.TELEPHONY_SERVICE);
Ecco Park4fa1ab72016-10-24 13:04:52 -0700530 CarrierConfigManager configManager = (CarrierConfigManager)
531 mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
Wink Savillea374c3d2014-11-11 11:48:04 -0800532 String mccMnc = phone.getSimOperator();
Ecco Park4fa1ab72016-10-24 13:04:52 -0700533 boolean isKeepLppProfile = false;
Wink Savillea374c3d2014-11-11 11:48:04 -0800534 if (!TextUtils.isEmpty(mccMnc)) {
Joe Onorato0c484102016-02-01 18:04:24 -0800535 if (DEBUG) Log.d(TAG, "SIM MCC/MNC is available: " + mccMnc);
Wink Savillea374c3d2014-11-11 11:48:04 -0800536 synchronized (mLock) {
Ecco Park4fa1ab72016-10-24 13:04:52 -0700537 if (configManager != null) {
538 PersistableBundle b = configManager.getConfig();
539 isKeepLppProfile = b.getBoolean(CarrierConfigManager.KEY_PERSIST_LPP_MODE_BOOL);
540 }
541 if (isKeepLppProfile) {
542 // load current properties for the carrier
543 loadPropertiesFromResource(context, mProperties);
544 String lpp_profile = mProperties.getProperty("LPP_PROFILE");
545 // set the persist property LPP_PROFILE for the value
546 SystemProperties.set(LPP_PROFILE, lpp_profile);
Ecco Park624ac3c2016-07-18 14:08:05 -0700547 } else {
Ecco Park4fa1ab72016-10-24 13:04:52 -0700548 // reset the persist property
549 SystemProperties.set(LPP_PROFILE, "");
Ecco Park624ac3c2016-07-18 14:08:05 -0700550 }
Wink Savillea374c3d2014-11-11 11:48:04 -0800551 reloadGpsProperties(context, mProperties);
552 mNIHandler.setSuplEsEnabled(mSuplEsEnabled);
553 }
554 } else {
Joe Onorato0c484102016-02-01 18:04:24 -0800555 if (DEBUG) Log.d(TAG, "SIM MCC/MNC is still not available");
Wink Savillea374c3d2014-11-11 11:48:04 -0800556 }
557 }
558
David Christied4edf4c2014-08-12 15:22:27 -0700559 private void updateLowPowerMode() {
Adam Lesinski87c17df2015-05-27 13:24:13 -0700560 // Disable GPS if we are in device idle mode.
561 boolean disableGps = mPowerManager.isDeviceIdleMode();
jackqdyulei455e90a2017-02-09 15:29:16 -0800562 final PowerSaveState result =
563 mPowerManager.getPowerSaveState(ServiceType.GPS);
564 switch (result.gpsMode) {
565 case BatterySaverPolicy.GPS_MODE_DISABLED_WHEN_SCREEN_OFF:
Adam Lesinski87c17df2015-05-27 13:24:13 -0700566 // If we are in battery saver mode and the screen is off, disable GPS.
jackqdyulei455e90a2017-02-09 15:29:16 -0800567 disableGps |= result.batterySaverEnabled && !mPowerManager.isInteractive();
David Christied4edf4c2014-08-12 15:22:27 -0700568 break;
David Christied4edf4c2014-08-12 15:22:27 -0700569 }
570 if (disableGps != mDisableGps) {
571 mDisableGps = disableGps;
572 updateRequirements();
573 }
574 }
575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 public static boolean isSupported() {
577 return native_is_supported();
578 }
579
Hridya Valsaraju2ea29602016-09-13 08:38:09 -0700580 interface SetCarrierProperty {
581 public boolean set(int value);
582 }
583
Tsuwei Chen52617bb2014-08-25 11:49:11 -0700584 private void reloadGpsProperties(Context context, Properties properties) {
Joe Onorato0c484102016-02-01 18:04:24 -0800585 if (DEBUG) Log.d(TAG, "Reset GPS properties, previous size = " + properties.size());
Tsuwei Chen52617bb2014-08-25 11:49:11 -0700586 loadPropertiesFromResource(context, properties);
Ecco Park624ac3c2016-07-18 14:08:05 -0700587
Ecco Park624ac3c2016-07-18 14:08:05 -0700588 String lpp_prof = SystemProperties.get(LPP_PROFILE);
589 if (!TextUtils.isEmpty(lpp_prof)) {
590 // override default value of this if lpp_prof is not empty
591 properties.setProperty("LPP_PROFILE", lpp_prof);
592 }
Wyatt Riley3e1cd0b2017-04-19 17:57:14 -0700593 /*
594 * Overlay carrier properties from a debug configuration file.
595 */
596 loadPropertiesFromFile(DEBUG_PROPERTIES_FILE, properties);
Tsuwei Chen52617bb2014-08-25 11:49:11 -0700597 // TODO: we should get rid of C2K specific setting.
598 setSuplHostPort(properties.getProperty("SUPL_HOST"),
599 properties.getProperty("SUPL_PORT"));
600 mC2KServerHost = properties.getProperty("C2K_HOST");
601 String portString = properties.getProperty("C2K_PORT");
602 if (mC2KServerHost != null && portString != null) {
603 try {
604 mC2KServerPort = Integer.parseInt(portString);
605 } catch (NumberFormatException e) {
606 Log.e(TAG, "unable to parse C2K_PORT: " + portString);
607 }
608 }
destradaaef752b62015-04-17 13:10:47 -0700609 if (native_is_gnss_configuration_supported()) {
Hridya Valsaraju2ea29602016-09-13 08:38:09 -0700610 Map<String, SetCarrierProperty> map = new HashMap<String, SetCarrierProperty>() {
611 {
612 put("SUPL_VER", (val) -> native_set_supl_version(val));
613 put("SUPL_MODE", (val) -> native_set_supl_mode(val));
614 put("SUPL_ES", (val) -> native_set_supl_es(val));
615 put("LPP_PROFILE", (val) -> native_set_lpp_profile(val));
616 put("A_GLONASS_POS_PROTOCOL_SELECT", (val) -> native_set_gnss_pos_protocol_select(val));
617 put("USE_EMERGENCY_PDN_FOR_EMERGENCY_SUPL", (val) -> native_set_emergency_supl_pdn(val));
618 put("GPS_LOCK", (val) -> native_set_gps_lock(val));
619 }
620 };
621
622 for(Entry<String, SetCarrierProperty> entry : map.entrySet()) {
623 String propertyName = entry.getKey();
624 String propertyValueString = properties.getProperty(propertyName);
625 if (propertyValueString != null) {
626 try {
627 int propertyValueInt = Integer.decode(propertyValueString);
628 boolean result = entry.getValue().set(propertyValueInt);
629 if (result == false) {
630 Log.e(TAG, "Unable to set " + propertyName);
631 }
632 } catch (NumberFormatException e) {
633 Log.e(TAG, "unable to parse propertyName: " + propertyValueString);
634 }
635 }
destradaaef752b62015-04-17 13:10:47 -0700636 }
637 } else if (DEBUG) {
638 Log.d(TAG, "Skipped configuration update because GNSS configuration in GPS HAL is not"
639 + " supported");
Tsuwei Chen52617bb2014-08-25 11:49:11 -0700640 }
Tsuwei Chen3324e952014-09-07 01:30:42 -0700641
642 // SUPL_ES configuration.
643 String suplESProperty = mProperties.getProperty("SUPL_ES");
644 if (suplESProperty != null) {
645 try {
646 mSuplEsEnabled = (Integer.parseInt(suplESProperty) == 1);
647 } catch (NumberFormatException e) {
648 Log.e(TAG, "unable to parse SUPL_ES: " + suplESProperty);
649 }
650 }
Tsuwei Chen52617bb2014-08-25 11:49:11 -0700651 }
652
653 private void loadPropertiesFromResource(Context context,
654 Properties properties) {
655 String[] configValues = context.getResources().getStringArray(
656 com.android.internal.R.array.config_gpsParameters);
657 for (String item : configValues) {
Joe Onorato0c484102016-02-01 18:04:24 -0800658 if (DEBUG) Log.d(TAG, "GpsParamsResource: " + item);
Tsuwei Chen7c485bf2014-09-10 15:33:34 -0700659 // We need to support "KEY =", but not "=VALUE".
Tsuwei Chen52617bb2014-08-25 11:49:11 -0700660 String[] split = item.split("=");
661 if (split.length == 2) {
662 properties.setProperty(split[0].trim().toUpperCase(), split[1]);
663 } else {
664 Log.w(TAG, "malformed contents: " + item);
665 }
666 }
667 }
668
669 private boolean loadPropertiesFromFile(String filename,
670 Properties properties) {
Colin Cross7c030ed2014-01-28 09:33:53 -0800671 try {
672 File file = new File(filename);
673 FileInputStream stream = null;
674 try {
675 stream = new FileInputStream(file);
Tsuwei Chen52617bb2014-08-25 11:49:11 -0700676 properties.load(stream);
Colin Cross7c030ed2014-01-28 09:33:53 -0800677 } finally {
678 IoUtils.closeQuietly(stream);
679 }
680
Colin Cross7c030ed2014-01-28 09:33:53 -0800681 } catch (IOException e) {
Wyatt Riley3e1cd0b2017-04-19 17:57:14 -0700682 if (DEBUG) Log.d(TAG, "Could not open GPS configuration file " + filename);
Colin Cross7c030ed2014-01-28 09:33:53 -0800683 return false;
684 }
685 return true;
686 }
687
Lifu Tang30f95a72016-01-07 23:20:38 -0800688 public GnssLocationProvider(Context context, ILocationManager ilocationManager,
Victoria Lease5cd731a2012-12-19 15:04:21 -0800689 Looper looper) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 mContext = context;
Jeff Sharkey104344e2011-07-10 14:20:41 -0700691 mNtpTime = NtpTrustedTime.getInstance(context);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700692 mILocationManager = ilocationManager;
Mike Lockwood63598a02010-02-24 11:52:59 -0500693
694 mLocation.setExtras(mLocationExtras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400696 // Create a wake lock
David Christied4edf4c2014-08-12 15:22:27 -0700697 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
698 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700699 mWakeLock.setReferenceCounted(true);
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400700
Wei Wangb71c0492017-05-01 20:24:19 -0700701 // Create a separate wake lock for xtra downloader as it may be released due to timeout.
702 mDownloadXtraWakeLock = mPowerManager.newWakeLock(
703 PowerManager.PARTIAL_WAKE_LOCK, DOWNLOAD_EXTRA_WAKELOCK_KEY);
704 mDownloadXtraWakeLock.setReferenceCounted(true);
705
Mike Lockwood29c84342009-05-06 14:01:15 -0400706 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
707 mWakeupIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ALARM_WAKEUP), 0);
Mike Lockwood0632ca72009-05-14 15:51:03 -0400708 mTimeoutIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ALARM_TIMEOUT), 0);
Mike Lockwood29c84342009-05-06 14:01:15 -0400709
Mike Lockwood58bda982009-04-14 16:25:07 -0400710 mConnMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
711
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800712 // App ops service to keep track of who is accessing the GPS
713 mAppOpsService = IAppOpsService.Stub.asInterface(ServiceManager.getService(
714 Context.APP_OPS_SERVICE));
715
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400716 // Battery statistics service to be notified when GPS turns on or off
Dianne Hackborn91268cf2013-06-13 19:06:50 -0700717 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
718 BatteryStats.SERVICE_NAME));
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400719
destradaafb23c672015-04-16 14:01:27 -0700720 // Construct internal handler
721 mHandler = new ProviderHandler(looper);
722
723 // Load GPS configuration and register listeners in the background:
724 // some operations, such as opening files and registering broadcast receivers, can take a
725 // relative long time, so the ctor() is kept to create objects needed by this instance,
726 // while IO initialization and registration is delegated to our internal handler
727 // this approach is just fine because events are posted to our handler anyway
Tsuwei Chen52617bb2014-08-25 11:49:11 -0700728 mProperties = new Properties();
destradaafb23c672015-04-16 14:01:27 -0700729 sendMessage(INITIALIZE_HANDLER, 0, null);
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400730
Tsuwei Chen3324e952014-09-07 01:30:42 -0700731 // Create a GPS net-initiated handler.
732 mNIHandler = new GpsNetInitiatedHandler(context,
733 mNetInitiatedListener,
734 mSuplEsEnabled);
735
Lifu Tang30f95a72016-01-07 23:20:38 -0800736 mListenerHelper = new GnssStatusListenerHelper(mHandler) {
destradaa6568d702014-10-27 12:47:41 -0700737 @Override
738 protected boolean isAvailableInPlatform() {
destradaa13a60b02015-01-15 18:36:01 -0800739 return isSupported();
destradaa6568d702014-10-27 12:47:41 -0700740 }
741
742 @Override
743 protected boolean isGpsEnabled() {
744 return isEnabled();
745 }
746 };
747
Lifu Tang818aa2c2016-02-01 01:52:00 -0800748 mGnssMeasurementsProvider = new GnssMeasurementsProvider(mHandler) {
destradaa6568d702014-10-27 12:47:41 -0700749 @Override
750 public boolean isAvailableInPlatform() {
751 return native_is_measurement_supported();
752 }
753
754 @Override
755 protected boolean registerWithService() {
756 return native_start_measurement_collection();
757 }
758
759 @Override
760 protected void unregisterFromService() {
761 native_stop_measurement_collection();
762 }
763
764 @Override
765 protected boolean isGpsEnabled() {
766 return isEnabled();
767 }
768 };
769
Lifu Tang818aa2c2016-02-01 01:52:00 -0800770 mGnssNavigationMessageProvider = new GnssNavigationMessageProvider(mHandler) {
destradaa6568d702014-10-27 12:47:41 -0700771 @Override
772 protected boolean isAvailableInPlatform() {
773 return native_is_navigation_message_supported();
774 }
775
776 @Override
777 protected boolean registerWithService() {
778 return native_start_navigation_message_collection();
779 }
780
781 @Override
782 protected void unregisterFromService() {
783 native_stop_navigation_message_collection();
784 }
785
786 @Override
787 protected boolean isGpsEnabled() {
788 return isEnabled();
789 }
790 };
Siddharth Raybb608c82017-03-16 11:33:34 -0700791 mGnssMetrics = new GnssMetrics();
Siddharth Rayfff3a9d2017-06-21 15:14:44 -0700792
793 /*
794 * A cycle of native_init() and native_cleanup() is needed so that callbacks are registered
795 * after bootup even when location is disabled. This will allow Emergency SUPL to work even
796 * when location is disabled before device restart.
797 * */
798 boolean isInitialized = native_init();
799 if(!isInitialized) {
800 Log.d(TAG, "Failed to initialize at bootup");
801 } else {
802 native_cleanup();
803 }
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400804 }
805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 /**
Mike Lockwoodd03ff942010-02-09 08:46:14 -0500807 * Returns the name of this provider.
808 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700809 @Override
Mike Lockwoodd03ff942010-02-09 08:46:14 -0500810 public String getName() {
811 return LocationManager.GPS_PROVIDER;
812 }
813
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700814 @Override
815 public ProviderProperties getProperties() {
816 return PROPERTIES;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 }
818
destradaae21252a2015-09-08 12:32:59 -0700819 private void handleUpdateNetworkState(Network network) {
820 // retrieve NetworkInfo for this UID
821 NetworkInfo info = mConnMgr.getNetworkInfo(network);
Kevin Tang71ad5fe2017-05-10 19:36:20 -0700822
823 boolean networkAvailable = false;
824 boolean isConnected = false;
825 int type = ConnectivityManager.TYPE_NONE;
826 boolean isRoaming = false;
827 String apnName = null;
828
829 if (info != null) {
830 networkAvailable = info.isAvailable() && TelephonyManager.getDefault().getDataEnabled();
831 isConnected = info.isConnected();
832 type = info.getType();
833 isRoaming = info.isRoaming();
834 apnName = info.getExtraInfo();
destradaae21252a2015-09-08 12:32:59 -0700835 }
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400836
Joe Onoratof5d95cb2010-01-07 21:48:32 -0500837 if (DEBUG) {
destradaae21252a2015-09-08 12:32:59 -0700838 String message = String.format(
839 "UpdateNetworkState, state=%s, connected=%s, info=%s, capabilities=%S",
840 agpsDataConnStateAsString(),
841 isConnected,
842 info,
843 mConnMgr.getNetworkCapabilities(network));
844 Log.d(TAG, message);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 }
Mike Lockwood03d24672009-10-08 15:45:03 -0400846
destradaae21252a2015-09-08 12:32:59 -0700847 if (native_is_agps_ril_supported()) {
destradaae21252a2015-09-08 12:32:59 -0700848 String defaultApn = getSelectedApn();
849 if (defaultApn == null) {
850 defaultApn = "dummy-apn";
destradaaef752b62015-04-17 13:10:47 -0700851 }
destradaae21252a2015-09-08 12:32:59 -0700852
853 native_update_network_state(
854 isConnected,
Kevin Tang71ad5fe2017-05-10 19:36:20 -0700855 type,
856 isRoaming,
destradaae21252a2015-09-08 12:32:59 -0700857 networkAvailable,
Kevin Tang71ad5fe2017-05-10 19:36:20 -0700858 apnName,
destradaae21252a2015-09-08 12:32:59 -0700859 defaultApn);
860 } else if (DEBUG) {
861 Log.d(TAG, "Skipped network state update because GPS HAL AGPS-RIL is not supported");
Mike Lockwood50130bb2010-10-11 06:22:50 -0400862 }
863
destradaae21252a2015-09-08 12:32:59 -0700864 if (mAGpsDataConnectionState == AGPS_DATA_CONNECTION_OPENING) {
865 if (isConnected) {
Stephen Li83b69712011-01-25 18:47:28 -0800866 if (apnName == null) {
destradaae21252a2015-09-08 12:32:59 -0700867 // assign a dummy value in the case of C2K as otherwise we will have a runtime
868 // exception in the following call to native_agps_data_conn_open
Stephen Li83b69712011-01-25 18:47:28 -0800869 apnName = "dummy-apn";
870 }
destradaae21252a2015-09-08 12:32:59 -0700871 int apnIpType = getApnIpType(apnName);
destradaa96a14702014-06-05 11:36:30 -0700872 setRouting();
873 if (DEBUG) {
874 String message = String.format(
875 "native_agps_data_conn_open: mAgpsApn=%s, mApnIpType=%s",
destradaae21252a2015-09-08 12:32:59 -0700876 apnName,
877 apnIpType);
destradaa96a14702014-06-05 11:36:30 -0700878 Log.d(TAG, message);
Stephen Li8efd74d2011-03-01 20:56:00 -0800879 }
destradaae21252a2015-09-08 12:32:59 -0700880 native_agps_data_conn_open(apnName, apnIpType);
Mike Lockwood03d24672009-10-08 15:45:03 -0400881 mAGpsDataConnectionState = AGPS_DATA_CONNECTION_OPEN;
882 } else {
destradaae21252a2015-09-08 12:32:59 -0700883 handleReleaseSuplConnection(GPS_AGPS_DATA_CONN_FAILED);
Mike Lockwood03d24672009-10-08 15:45:03 -0400884 }
885 }
destradaae21252a2015-09-08 12:32:59 -0700886 }
Mike Lockwood03d24672009-10-08 15:45:03 -0400887
destradaae21252a2015-09-08 12:32:59 -0700888 private void handleRequestSuplConnection(InetAddress address) {
889 if (DEBUG) {
890 String message = String.format(
891 "requestSuplConnection, state=%s, address=%s",
892 agpsDataConnStateAsString(),
893 address);
894 Log.d(TAG, message);
895 }
896
897 if (mAGpsDataConnectionState != AGPS_DATA_CONNECTION_CLOSED) {
898 return;
899 }
900 mAGpsDataConnectionIpAddr = address;
901 mAGpsDataConnectionState = AGPS_DATA_CONNECTION_OPENING;
902
903 NetworkRequest.Builder requestBuilder = new NetworkRequest.Builder();
904 requestBuilder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
905 requestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_SUPL);
906 NetworkRequest request = requestBuilder.build();
907 mConnMgr.requestNetwork(
908 request,
Etan Cohene9aea9d2017-02-09 18:16:58 -0800909 mSuplConnectivityCallback);
destradaae21252a2015-09-08 12:32:59 -0700910 }
911
912 private void handleReleaseSuplConnection(int agpsDataConnStatus) {
913 if (DEBUG) {
914 String message = String.format(
915 "releaseSuplConnection, state=%s, status=%s",
916 agpsDataConnStateAsString(),
917 agpsDataConnStatusAsString(agpsDataConnStatus));
918 Log.d(TAG, message);
919 }
920
921 if (mAGpsDataConnectionState == AGPS_DATA_CONNECTION_CLOSED) {
922 return;
923 }
924 mAGpsDataConnectionState = AGPS_DATA_CONNECTION_CLOSED;
925
926 mConnMgr.unregisterNetworkCallback(mSuplConnectivityCallback);
927 switch (agpsDataConnStatus) {
928 case GPS_AGPS_DATA_CONN_FAILED:
929 native_agps_data_conn_failed();
930 break;
931 case GPS_RELEASE_AGPS_DATA_CONN:
932 native_agps_data_conn_closed();
933 break;
934 default:
935 Log.e(TAG, "Invalid status to release SUPL connection: " + agpsDataConnStatus);
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400936 }
937 }
938
939 private void handleInjectNtpTime() {
Kevin Tang40e1baf2012-01-10 14:32:44 -0800940 if (mInjectNtpTimePending == STATE_DOWNLOADING) {
941 // already downloading data
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400942 return;
943 }
destradaae21252a2015-09-08 12:32:59 -0700944 if (!isDataNetworkConnected()) {
Kevin Tang40e1baf2012-01-10 14:32:44 -0800945 // try again when network is up
946 mInjectNtpTimePending = STATE_PENDING_NETWORK;
947 return;
Jeff Sharkey104344e2011-07-10 14:20:41 -0700948 }
Kevin Tang40e1baf2012-01-10 14:32:44 -0800949 mInjectNtpTimePending = STATE_DOWNLOADING;
Jeff Sharkey104344e2011-07-10 14:20:41 -0700950
Jeff Brown028872f2012-08-25 13:07:01 -0700951 // hold wake lock while task runs
952 mWakeLock.acquire();
Lifu Tangcbd2a142016-06-22 10:57:55 -0700953 Log.i(TAG, "WakeLock acquired by handleInjectNtpTime()");
Kevin Tang40e1baf2012-01-10 14:32:44 -0800954 AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
955 @Override
956 public void run() {
957 long delay;
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400958
Kevin Tang40e1baf2012-01-10 14:32:44 -0800959 // force refresh NTP cache when outdated
destradaa56b47f82015-07-24 10:56:18 -0700960 boolean refreshSuccess = true;
Kevin Tang40e1baf2012-01-10 14:32:44 -0800961 if (mNtpTime.getCacheAge() >= NTP_INTERVAL) {
destradaa56b47f82015-07-24 10:56:18 -0700962 refreshSuccess = mNtpTime.forceRefresh();
Kevin Tang40e1baf2012-01-10 14:32:44 -0800963 }
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400964
Kevin Tang40e1baf2012-01-10 14:32:44 -0800965 // only update when NTP time is fresh
966 if (mNtpTime.getCacheAge() < NTP_INTERVAL) {
967 long time = mNtpTime.getCachedNtpTime();
968 long timeReference = mNtpTime.getCachedNtpTimeReference();
969 long certainty = mNtpTime.getCacheCertainty();
Mike Lockwood62a8fc12010-03-22 14:23:26 -0400970
Joe Onorato0c484102016-02-01 18:04:24 -0800971 if (DEBUG) {
Yipeng Cao276278d2017-05-18 13:27:30 -0700972 long now = System.currentTimeMillis();
Joe Onorato0c484102016-02-01 18:04:24 -0800973 Log.d(TAG, "NTP server returned: "
974 + time + " (" + new Date(time)
975 + ") reference: " + timeReference
976 + " certainty: " + certainty
977 + " system time offset: " + (time - now));
978 }
Kevin Tang40e1baf2012-01-10 14:32:44 -0800979
980 native_inject_time(time, timeReference, (int) certainty);
981 delay = NTP_INTERVAL;
Wei Liu6f6326b2015-06-24 23:47:50 -0700982 mNtpBackOff.reset();
Kevin Tang40e1baf2012-01-10 14:32:44 -0800983 } else {
destradaa56b47f82015-07-24 10:56:18 -0700984 Log.e(TAG, "requestTime failed");
Wei Liu6f6326b2015-06-24 23:47:50 -0700985 delay = mNtpBackOff.nextBackoffMillis();
Kevin Tang40e1baf2012-01-10 14:32:44 -0800986 }
987
Jeff Brown028872f2012-08-25 13:07:01 -0700988 sendMessage(INJECT_NTP_TIME_FINISHED, 0, null);
Kevin Tang40e1baf2012-01-10 14:32:44 -0800989
destradaa56b47f82015-07-24 10:56:18 -0700990 if (DEBUG) {
991 String message = String.format(
992 "onDemandTimeInjection=%s, refreshSuccess=%s, delay=%s",
993 mOnDemandTimeInjection,
994 refreshSuccess,
995 delay);
996 Log.d(TAG, message);
997 }
998 if (mOnDemandTimeInjection || !refreshSuccess) {
Kevin Tang40e1baf2012-01-10 14:32:44 -0800999 // send delayed message for next NTP injection
1000 // since this is delayed and not urgent we do not hold a wake lock here
Jeff Brown028872f2012-08-25 13:07:01 -07001001 mHandler.sendEmptyMessageDelayed(INJECT_NTP_TIME, delay);
Kevin Tang40e1baf2012-01-10 14:32:44 -08001002 }
Jeff Brown028872f2012-08-25 13:07:01 -07001003
1004 // release wake lock held by task
1005 mWakeLock.release();
Lifu Tangcbd2a142016-06-22 10:57:55 -07001006 Log.i(TAG, "WakeLock released by handleInjectNtpTime()");
Kevin Tang40e1baf2012-01-10 14:32:44 -08001007 }
1008 });
Mike Lockwood62a8fc12010-03-22 14:23:26 -04001009 }
1010
1011 private void handleDownloadXtraData() {
Wyatt Riley0d6e54e22016-10-05 12:03:03 -07001012 if (!mSupportsXtra) {
1013 // native code reports xtra not supported, don't try
1014 Log.d(TAG, "handleDownloadXtraData() called when Xtra not supported");
1015 return;
1016 }
Kevin Tang40e1baf2012-01-10 14:32:44 -08001017 if (mDownloadXtraDataPending == STATE_DOWNLOADING) {
1018 // already downloading data
Mike Lockwood62a8fc12010-03-22 14:23:26 -04001019 return;
1020 }
destradaae21252a2015-09-08 12:32:59 -07001021 if (!isDataNetworkConnected()) {
Kevin Tang40e1baf2012-01-10 14:32:44 -08001022 // try again when network is up
1023 mDownloadXtraDataPending = STATE_PENDING_NETWORK;
1024 return;
Mike Lockwood62a8fc12010-03-22 14:23:26 -04001025 }
Kevin Tang40e1baf2012-01-10 14:32:44 -08001026 mDownloadXtraDataPending = STATE_DOWNLOADING;
1027
Jeff Brown028872f2012-08-25 13:07:01 -07001028 // hold wake lock while task runs
Wei Wangb71c0492017-05-01 20:24:19 -07001029 mDownloadXtraWakeLock.acquire(DOWNLOAD_XTRA_DATA_TIMEOUT_MS);
Lifu Tangcbd2a142016-06-22 10:57:55 -07001030 Log.i(TAG, "WakeLock acquired by handleDownloadXtraData()");
Kevin Tang40e1baf2012-01-10 14:32:44 -08001031 AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
1032 @Override
1033 public void run() {
Andreas Gampedfdc6ac2014-10-28 20:42:53 -07001034 GpsXtraDownloader xtraDownloader = new GpsXtraDownloader(mProperties);
Kevin Tang40e1baf2012-01-10 14:32:44 -08001035 byte[] data = xtraDownloader.downloadXtraData();
1036 if (data != null) {
destradaae21252a2015-09-08 12:32:59 -07001037 if (DEBUG) Log.d(TAG, "calling native_inject_xtra_data");
Kevin Tang40e1baf2012-01-10 14:32:44 -08001038 native_inject_xtra_data(data, data.length);
Wei Liu6f6326b2015-06-24 23:47:50 -07001039 mXtraBackOff.reset();
Kevin Tang40e1baf2012-01-10 14:32:44 -08001040 }
1041
Jeff Brown028872f2012-08-25 13:07:01 -07001042 sendMessage(DOWNLOAD_XTRA_DATA_FINISHED, 0, null);
Kevin Tang40e1baf2012-01-10 14:32:44 -08001043
1044 if (data == null) {
1045 // try again later
1046 // since this is delayed and not urgent we do not hold a wake lock here
Wei Liu6f6326b2015-06-24 23:47:50 -07001047 mHandler.sendEmptyMessageDelayed(DOWNLOAD_XTRA_DATA,
1048 mXtraBackOff.nextBackoffMillis());
Kevin Tang40e1baf2012-01-10 14:32:44 -08001049 }
Kevin Tang40e1baf2012-01-10 14:32:44 -08001050
Wei Wangb71c0492017-05-01 20:24:19 -07001051 // Release wake lock held by task, synchronize on mLock in case multiple
1052 // download tasks overrun.
1053 synchronized (mLock) {
1054 if (mDownloadXtraWakeLock.isHeld()) {
1055 mDownloadXtraWakeLock.release();
1056 if (DEBUG) Log.d(TAG, "WakeLock released by handleDownloadXtraData()");
1057 } else {
1058 Log.e(TAG, "WakeLock expired before release in "
1059 + "handleDownloadXtraData()");
1060 }
Wei Wangc5706f62017-04-18 11:26:26 -07001061 }
Jeff Brown028872f2012-08-25 13:07:01 -07001062 }
Kevin Tang40e1baf2012-01-10 14:32:44 -08001063 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 }
1065
Mike Lockwood62a8fc12010-03-22 14:23:26 -04001066 private void handleUpdateLocation(Location location) {
Mike Lockwoodd26ce0d2009-06-11 12:25:46 -04001067 if (location.hasAccuracy()) {
1068 native_inject_location(location.getLatitude(), location.getLongitude(),
1069 location.getAccuracy());
1070 }
Mike Lockwoodfd6e5f02009-05-21 11:28:20 -04001071 }
1072
1073 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 * Enables this provider. When enabled, calls to getStatus()
Mike Lockwood4e50b782009-04-03 08:24:43 -07001075 * must be handled. Hardware may be started up
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 * when the provider is enabled.
1077 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001078 @Override
Mike Lockwood62a8fc12010-03-22 14:23:26 -04001079 public void enable() {
Laurent Tu7b5aeca2013-01-24 15:10:24 -08001080 synchronized (mLock) {
1081 if (mEnabled) return;
1082 mEnabled = true;
1083 }
1084
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001085 sendMessage(ENABLE, 1, null);
Mike Lockwood62a8fc12010-03-22 14:23:26 -04001086 }
1087
Tsuwei Chen52617bb2014-08-25 11:49:11 -07001088 private void setSuplHostPort(String hostString, String portString) {
1089 if (hostString != null) {
1090 mSuplServerHost = hostString;
1091 }
1092 if (portString != null) {
1093 try {
1094 mSuplServerPort = Integer.parseInt(portString);
1095 } catch (NumberFormatException e) {
1096 Log.e(TAG, "unable to parse SUPL_PORT: " + portString);
1097 }
1098 }
Tsuwei Chen678c13c2014-09-22 17:48:41 -07001099 if (mSuplServerHost != null
1100 && mSuplServerPort > TCP_MIN_PORT
1101 && mSuplServerPort <= TCP_MAX_PORT) {
1102 native_set_agps_server(AGPS_TYPE_SUPL, mSuplServerHost, mSuplServerPort);
1103 }
Tsuwei Chen52617bb2014-08-25 11:49:11 -07001104 }
1105
Tsuwei Chen462bcd82014-09-17 12:28:49 -07001106 /**
1107 * Checks what SUPL mode to use, according to the AGPS mode as well as the
1108 * allowed mode from properties.
1109 *
1110 * @param properties GPS properties
1111 * @param agpsEnabled whether AGPS is enabled by settings value
1112 * @param singleShot whether "singleshot" is needed
1113 * @return SUPL mode (MSA vs MSB vs STANDALONE)
1114 */
1115 private int getSuplMode(Properties properties, boolean agpsEnabled, boolean singleShot) {
1116 if (agpsEnabled) {
1117 String modeString = properties.getProperty("SUPL_MODE");
1118 int suplMode = 0;
1119 if (!TextUtils.isEmpty(modeString)) {
1120 try {
1121 suplMode = Integer.parseInt(modeString);
1122 } catch (NumberFormatException e) {
1123 Log.e(TAG, "unable to parse SUPL_MODE: " + modeString);
1124 return GPS_POSITION_MODE_STANDALONE;
1125 }
1126 }
destradaabfb3bdb2015-04-29 14:42:35 -07001127 // MS-Based is the preferred mode for Assisted-GPS position computation, so we favor
1128 // such mode when it is available
1129 if (hasCapability(GPS_CAPABILITY_MSB) && (suplMode & AGPS_SUPL_MODE_MSB) != 0) {
1130 return GPS_POSITION_MODE_MS_BASED;
1131 }
1132 // for now, just as the legacy code did, we fallback to MS-Assisted if it is available,
1133 // do fallback only for single-shot requests, because it is too expensive to do for
1134 // periodic requests as well
Tsuwei Chen462bcd82014-09-17 12:28:49 -07001135 if (singleShot
1136 && hasCapability(GPS_CAPABILITY_MSA)
1137 && (suplMode & AGPS_SUPL_MODE_MSA) != 0) {
1138 return GPS_POSITION_MODE_MS_ASSISTED;
Tsuwei Chen462bcd82014-09-17 12:28:49 -07001139 }
1140 }
1141 return GPS_POSITION_MODE_STANDALONE;
1142 }
1143
Mike Lockwood62a8fc12010-03-22 14:23:26 -04001144 private void handleEnable() {
1145 if (DEBUG) Log.d(TAG, "handleEnable");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001147 boolean enabled = native_init();
1148
1149 if (enabled) {
Mike Lockwood1a1cd3a2010-08-17 07:42:54 -04001150 mSupportsXtra = native_supports_xtra();
Tsuwei Chen678c13c2014-09-22 17:48:41 -07001151
1152 // TODO: remove the following native calls if we can make sure they are redundant.
Mike Lockwood734d6032009-07-28 18:30:25 -07001153 if (mSuplServerHost != null) {
1154 native_set_agps_server(AGPS_TYPE_SUPL, mSuplServerHost, mSuplServerPort);
1155 }
1156 if (mC2KServerHost != null) {
1157 native_set_agps_server(AGPS_TYPE_C2K, mC2KServerHost, mC2KServerPort);
1158 }
destradaa13a60b02015-01-15 18:36:01 -08001159
Lifu Tang818aa2c2016-02-01 01:52:00 -08001160 mGnssMeasurementsProvider.onGpsEnabledChanged();
1161 mGnssNavigationMessageProvider.onGpsEnabledChanged();
Wyatt Rileycf879db2017-01-12 13:57:38 -08001162 enableBatching();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 } else {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001164 synchronized (mLock) {
1165 mEnabled = false;
1166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 Log.w(TAG, "Failed to enable location provider");
1168 }
1169 }
1170
1171 /**
1172 * Disables this provider. When disabled, calls to getStatus()
Mike Lockwood4e50b782009-04-03 08:24:43 -07001173 * need not be handled. Hardware may be shut
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 * down while the provider is disabled.
1175 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001176 @Override
Mike Lockwood62a8fc12010-03-22 14:23:26 -04001177 public void disable() {
Laurent Tu7b5aeca2013-01-24 15:10:24 -08001178 synchronized (mLock) {
1179 if (!mEnabled) return;
1180 mEnabled = false;
1181 }
1182
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001183 sendMessage(ENABLE, 0, null);
Mike Lockwood62a8fc12010-03-22 14:23:26 -04001184 }
1185
1186 private void handleDisable() {
Mike Lockwood89096312010-03-24 10:14:55 -04001187 if (DEBUG) Log.d(TAG, "handleDisable");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188
David Christie3bc26142013-12-19 14:53:44 -08001189 updateClientUids(new WorkSource());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 stopNavigating();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001191 mAlarmManager.cancel(mWakeupIntent);
1192 mAlarmManager.cancel(mTimeoutIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193
Wyatt Rileycf879db2017-01-12 13:57:38 -08001194 disableBatching();
Mike Lockwoodcf1d8cb2010-01-20 10:14:54 -05001195 // do this before releasing wakelock
1196 native_cleanup();
destradaa13a60b02015-01-15 18:36:01 -08001197
Lifu Tang818aa2c2016-02-01 01:52:00 -08001198 mGnssMeasurementsProvider.onGpsEnabledChanged();
1199 mGnssNavigationMessageProvider.onGpsEnabledChanged();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 }
1201
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001202 @Override
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001203 public boolean isEnabled() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001204 synchronized (mLock) {
1205 return mEnabled;
1206 }
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001207 }
1208
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001209 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 public int getStatus(Bundle extras) {
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001211 setLocationExtras(extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 return mStatus;
1213 }
1214
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001215 private void updateStatus(int status, int svCount, int meanCn0, int maxCn0) {
1216 if (status != mStatus || svCount != mSvCount || meanCn0 != mMeanCn0 || maxCn0 != mMaxCn0 ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 mStatus = status;
1218 mSvCount = svCount;
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001219 mMeanCn0 = meanCn0;
1220 mMaxCn0 = maxCn0;
1221 setLocationExtras(mLocationExtras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 mStatusUpdateTime = SystemClock.elapsedRealtime();
1223 }
1224 }
1225
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001226 private void setLocationExtras(Bundle extras) {
1227 if (extras != null) {
1228 extras.putInt("satellites", mSvCount);
1229 extras.putInt("meanCn0", mMeanCn0);
1230 extras.putInt("maxCn0", mMaxCn0);
1231 }
1232 }
1233
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001234 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 public long getStatusUpdateTime() {
1236 return mStatusUpdateTime;
1237 }
1238
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001239 @Override
1240 public void setRequest(ProviderRequest request, WorkSource source) {
1241 sendMessage(SET_REQUEST, 0, new GpsRequest(request, source));
Mike Lockwood62a8fc12010-03-22 14:23:26 -04001242 }
1243
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001244 private void handleSetRequest(ProviderRequest request, WorkSource source) {
David Christied4edf4c2014-08-12 15:22:27 -07001245 mProviderRequest = request;
1246 mWorkSource = source;
1247 updateRequirements();
1248 }
1249
1250 // Called when the requirements for GPS may have changed
1251 private void updateRequirements() {
1252 if (mProviderRequest == null || mWorkSource == null) {
1253 return;
1254 }
1255
Stan Chesnutt1d72d8c2013-04-15 19:18:02 -07001256 boolean singleShot = false;
1257
1258 // see if the request is for a single update
David Christied4edf4c2014-08-12 15:22:27 -07001259 if (mProviderRequest.locationRequests != null
1260 && mProviderRequest.locationRequests.size() > 0) {
Stan Chesnutt1d72d8c2013-04-15 19:18:02 -07001261 // if any request has zero or more than one updates
1262 // requested, then this is not single-shot mode
1263 singleShot = true;
1264
David Christied4edf4c2014-08-12 15:22:27 -07001265 for (LocationRequest lr : mProviderRequest.locationRequests) {
Stan Chesnutt1d72d8c2013-04-15 19:18:02 -07001266 if (lr.getNumUpdates() != 1) {
1267 singleShot = false;
1268 }
1269 }
1270 }
1271
David Christied4edf4c2014-08-12 15:22:27 -07001272 if (DEBUG) Log.d(TAG, "setRequest " + mProviderRequest);
Dante Russo260d6672016-06-20 11:11:59 -07001273 if (mProviderRequest.reportLocation && !mDisableGps && isEnabled()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001274 // update client uids
David Christied4edf4c2014-08-12 15:22:27 -07001275 updateClientUids(mWorkSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276
David Christied4edf4c2014-08-12 15:22:27 -07001277 mFixInterval = (int) mProviderRequest.interval;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001278
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001279 // check for overflow
David Christied4edf4c2014-08-12 15:22:27 -07001280 if (mFixInterval != mProviderRequest.interval) {
1281 Log.w(TAG, "interval overflow: " + mProviderRequest.interval);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001282 mFixInterval = Integer.MAX_VALUE;
1283 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001284
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001285 // apply request to GPS engine
Mike Lockwood04598b62010-04-14 17:17:24 -04001286 if (mStarted && hasCapability(GPS_CAPABILITY_SCHEDULING)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001287 // change period
Mike Lockwood04598b62010-04-14 17:17:24 -04001288 if (!native_set_position_mode(mPositionMode, GPS_POSITION_RECURRENCE_PERIODIC,
1289 mFixInterval, 0, 0)) {
1290 Log.e(TAG, "set_position_mode failed in setMinTime()");
1291 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001292 } else if (!mStarted) {
1293 // start GPS
Stan Chesnutt1d72d8c2013-04-15 19:18:02 -07001294 startNavigating(singleShot);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001296 } else {
Dianne Hackborn002a54e2013-01-10 17:34:55 -08001297 updateClientUids(new WorkSource());
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001298
1299 stopNavigating();
1300 mAlarmManager.cancel(mWakeupIntent);
1301 mAlarmManager.cancel(mTimeoutIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 }
1303 }
1304
Dianne Hackborn002a54e2013-01-10 17:34:55 -08001305 private void updateClientUids(WorkSource source) {
1306 // Update work source.
1307 WorkSource[] changes = mClientSource.setReturningDiffs(source);
Victoria Leaseea78b852013-01-15 10:39:28 -08001308 if (changes == null) {
1309 return;
1310 }
Dianne Hackborn002a54e2013-01-10 17:34:55 -08001311 WorkSource newWork = changes[0];
1312 WorkSource goneWork = changes[1];
1313
1314 // Update sources that were not previously tracked.
1315 if (newWork != null) {
1316 int lastuid = -1;
1317 for (int i=0; i<newWork.size(); i++) {
Dianne Hackborn2e418422009-06-22 20:00:17 -07001318 try {
Dianne Hackborn002a54e2013-01-10 17:34:55 -08001319 int uid = newWork.get(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001320 mAppOpsService.startOperation(AppOpsManager.getToken(mAppOpsService),
1321 AppOpsManager.OP_GPS, uid, newWork.getName(i));
Dianne Hackborn002a54e2013-01-10 17:34:55 -08001322 if (uid != lastuid) {
1323 lastuid = uid;
1324 mBatteryStats.noteStartGps(uid);
1325 }
Dianne Hackborn2e418422009-06-22 20:00:17 -07001326 } catch (RemoteException e) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001327 Log.w(TAG, "RemoteException", e);
1328 }
1329 }
1330 }
1331
Dianne Hackborn002a54e2013-01-10 17:34:55 -08001332 // Update sources that are no longer tracked.
1333 if (goneWork != null) {
1334 int lastuid = -1;
1335 for (int i=0; i<goneWork.size(); i++) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001336 try {
Dianne Hackborn002a54e2013-01-10 17:34:55 -08001337 int uid = goneWork.get(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001338 mAppOpsService.finishOperation(AppOpsManager.getToken(mAppOpsService),
1339 AppOpsManager.OP_GPS, uid, goneWork.getName(i));
Dianne Hackborn002a54e2013-01-10 17:34:55 -08001340 if (uid != lastuid) {
1341 lastuid = uid;
1342 mBatteryStats.noteStopGps(uid);
1343 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001344 } catch (RemoteException e) {
1345 Log.w(TAG, "RemoteException", e);
Dianne Hackborn2e418422009-06-22 20:00:17 -07001346 }
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001347 }
1348 }
1349 }
1350
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001351 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 public boolean sendExtraCommand(String command, Bundle extras) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001353
Mike Lockwood63aa5a62010-04-14 19:21:31 -04001354 long identity = Binder.clearCallingIdentity();
1355 boolean result = false;
1356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 if ("delete_aiding_data".equals(command)) {
Mike Lockwood63aa5a62010-04-14 19:21:31 -04001358 result = deleteAidingData(extras);
1359 } else if ("force_time_injection".equals(command)) {
destradaae21252a2015-09-08 12:32:59 -07001360 requestUtcTime();
Mike Lockwood63aa5a62010-04-14 19:21:31 -04001361 result = true;
1362 } else if ("force_xtra_injection".equals(command)) {
Mike Lockwood1a1cd3a2010-08-17 07:42:54 -04001363 if (mSupportsXtra) {
Mike Lockwood93bc44d2009-05-20 16:58:22 -04001364 xtraDownloadRequest();
Mike Lockwood63aa5a62010-04-14 19:21:31 -04001365 result = true;
Mike Lockwood93bc44d2009-05-20 16:58:22 -04001366 }
Mike Lockwood63aa5a62010-04-14 19:21:31 -04001367 } else {
1368 Log.w(TAG, "sendExtraCommand: unknown command " + command);
Mike Lockwood93bc44d2009-05-20 16:58:22 -04001369 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001370
Mike Lockwood63aa5a62010-04-14 19:21:31 -04001371 Binder.restoreCallingIdentity(identity);
1372 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 }
1374
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001375 private IGpsGeofenceHardware mGpsGeofenceBinder = new IGpsGeofenceHardware.Stub() {
1376 public boolean isHardwareGeofenceSupported() {
1377 return native_is_geofence_supported();
1378 }
1379
1380 public boolean addCircularHardwareGeofence(int geofenceId, double latitude,
1381 double longitude, double radius, int lastTransition, int monitorTransitions,
1382 int notificationResponsiveness, int unknownTimer) {
1383 return native_add_geofence(geofenceId, latitude, longitude, radius,
1384 lastTransition, monitorTransitions, notificationResponsiveness, unknownTimer);
1385 }
1386
1387 public boolean removeHardwareGeofence(int geofenceId) {
1388 return native_remove_geofence(geofenceId);
1389 }
1390
1391 public boolean pauseHardwareGeofence(int geofenceId) {
1392 return native_pause_geofence(geofenceId);
1393 }
1394
1395 public boolean resumeHardwareGeofence(int geofenceId, int monitorTransition) {
1396 return native_resume_geofence(geofenceId, monitorTransition);
1397 }
1398 };
1399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 private boolean deleteAidingData(Bundle extras) {
1401 int flags;
1402
1403 if (extras == null) {
1404 flags = GPS_DELETE_ALL;
1405 } else {
1406 flags = 0;
1407 if (extras.getBoolean("ephemeris")) flags |= GPS_DELETE_EPHEMERIS;
1408 if (extras.getBoolean("almanac")) flags |= GPS_DELETE_ALMANAC;
1409 if (extras.getBoolean("position")) flags |= GPS_DELETE_POSITION;
1410 if (extras.getBoolean("time")) flags |= GPS_DELETE_TIME;
1411 if (extras.getBoolean("iono")) flags |= GPS_DELETE_IONO;
1412 if (extras.getBoolean("utc")) flags |= GPS_DELETE_UTC;
1413 if (extras.getBoolean("health")) flags |= GPS_DELETE_HEALTH;
1414 if (extras.getBoolean("svdir")) flags |= GPS_DELETE_SVDIR;
1415 if (extras.getBoolean("svsteer")) flags |= GPS_DELETE_SVSTEER;
1416 if (extras.getBoolean("sadata")) flags |= GPS_DELETE_SADATA;
1417 if (extras.getBoolean("rti")) flags |= GPS_DELETE_RTI;
1418 if (extras.getBoolean("celldb-info")) flags |= GPS_DELETE_CELLDB_INFO;
1419 if (extras.getBoolean("all")) flags |= GPS_DELETE_ALL;
1420 }
1421
1422 if (flags != 0) {
1423 native_delete_aiding_data(flags);
1424 return true;
1425 }
1426
1427 return false;
1428 }
1429
Stan Chesnutt1d72d8c2013-04-15 19:18:02 -07001430 private void startNavigating(boolean singleShot) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 if (!mStarted) {
Stan Chesnutt1d72d8c2013-04-15 19:18:02 -07001432 if (DEBUG) Log.d(TAG, "startNavigating, singleShot is " + singleShot);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001433 mTimeToFirstFix = 0;
1434 mLastFixTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 mStarted = true;
Stan Chesnutt1d72d8c2013-04-15 19:18:02 -07001436 mSingleShot = singleShot;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001437 mPositionMode = GPS_POSITION_MODE_STANDALONE;
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001438 // Notify about suppressed output, if speed limit was previously exceeded.
1439 // Elsewhere, we check again with every speed output reported.
1440 if (mItarSpeedLimitExceeded) {
1441 Log.i(TAG, "startNavigating with ITAR limit in place. Output limited " +
1442 "until slow enough speed reported.");
1443 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001444
Tsuwei Chen462bcd82014-09-17 12:28:49 -07001445 boolean agpsEnabled =
1446 (Settings.Global.getInt(mContext.getContentResolver(),
1447 Settings.Global.ASSISTED_GPS_ENABLED, 1) != 0);
1448 mPositionMode = getSuplMode(mProperties, agpsEnabled, singleShot);
Mike Lockwoodbcab8df2009-06-25 16:39:09 -04001449
Stan Chesnutt1d72d8c2013-04-15 19:18:02 -07001450 if (DEBUG) {
1451 String mode;
1452
1453 switch(mPositionMode) {
1454 case GPS_POSITION_MODE_STANDALONE:
1455 mode = "standalone";
1456 break;
1457 case GPS_POSITION_MODE_MS_ASSISTED:
1458 mode = "MS_ASSISTED";
1459 break;
1460 case GPS_POSITION_MODE_MS_BASED:
1461 mode = "MS_BASED";
1462 break;
1463 default:
1464 mode = "unknown";
1465 break;
1466 }
1467 Log.d(TAG, "setting position_mode to " + mode);
1468 }
1469
Mike Lockwood04598b62010-04-14 17:17:24 -04001470 int interval = (hasCapability(GPS_CAPABILITY_SCHEDULING) ? mFixInterval : 1000);
1471 if (!native_set_position_mode(mPositionMode, GPS_POSITION_RECURRENCE_PERIODIC,
1472 interval, 0, 0)) {
1473 mStarted = false;
1474 Log.e(TAG, "set_position_mode failed in startNavigating()");
1475 return;
1476 }
1477 if (!native_start()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 mStarted = false;
1479 Log.e(TAG, "native_start failed in startNavigating()");
Mike Lockwood0632ca72009-05-14 15:51:03 -04001480 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 }
1482
1483 // reset SV count to zero
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001484 updateStatus(LocationProvider.TEMPORARILY_UNAVAILABLE, 0, 0, 0);
Yipeng Cao282b5942017-05-17 20:31:39 -07001485 mFixRequestTime = SystemClock.elapsedRealtime();
Mike Lockwood04598b62010-04-14 17:17:24 -04001486 if (!hasCapability(GPS_CAPABILITY_SCHEDULING)) {
1487 // set timer to give up if we do not receive a fix within NO_FIX_TIMEOUT
1488 // and our fix interval is not short
1489 if (mFixInterval >= NO_FIX_TIMEOUT) {
1490 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1491 SystemClock.elapsedRealtime() + NO_FIX_TIMEOUT, mTimeoutIntent);
1492 }
Mike Lockwood0632ca72009-05-14 15:51:03 -04001493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 }
1495 }
1496
Mike Lockwood62a8fc12010-03-22 14:23:26 -04001497 private void stopNavigating() {
Mike Lockwood29c84342009-05-06 14:01:15 -04001498 if (DEBUG) Log.d(TAG, "stopNavigating");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 if (mStarted) {
1500 mStarted = false;
Stan Chesnutt1d72d8c2013-04-15 19:18:02 -07001501 mSingleShot = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 native_stop();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001503 mTimeToFirstFix = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 mLastFixTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505
1506 // reset SV count to zero
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001507 updateStatus(LocationProvider.TEMPORARILY_UNAVAILABLE, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 }
1509 }
1510
Mike Lockwood0632ca72009-05-14 15:51:03 -04001511 private void hibernate() {
1512 // stop GPS until our next fix interval arrives
1513 stopNavigating();
Mike Lockwood0632ca72009-05-14 15:51:03 -04001514 mAlarmManager.cancel(mTimeoutIntent);
1515 mAlarmManager.cancel(mWakeupIntent);
1516 long now = SystemClock.elapsedRealtime();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001517 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, now + mFixInterval, mWakeupIntent);
Mike Lockwood04598b62010-04-14 17:17:24 -04001518 }
1519
1520 private boolean hasCapability(int capability) {
1521 return ((mEngineCapabilities & capability) != 0);
Mike Lockwood0632ca72009-05-14 15:51:03 -04001522 }
1523
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 /**
1526 * called from native code to update our position.
1527 */
Wyatt Riley5d229832017-02-10 17:06:00 -08001528 private void reportLocation(boolean hasLatLong, Location location) {
1529 if (location.hasSpeed()) {
1530 mItarSpeedLimitExceeded = location.getSpeed() > ITAR_SPEED_LIMIT_METERS_PER_SECOND;
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001531 }
1532
1533 if (mItarSpeedLimitExceeded) {
1534 Log.i(TAG, "Hal reported a speed in excess of ITAR limit." +
1535 " GPS/GNSS Navigation output blocked.");
Siddharth Raybb608c82017-03-16 11:33:34 -07001536 mGnssMetrics.logReceivedLocationStatus(false);
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001537 return; // No output of location allowed
1538 }
1539
Wyatt Riley5d229832017-02-10 17:06:00 -08001540 if (VERBOSE) Log.v(TAG, "reportLocation " + location.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 synchronized (mLocation) {
Wyatt Riley5d229832017-02-10 17:06:00 -08001543 mLocation = location;
1544 // It would be nice to push the elapsed real-time timestamp
1545 // further down the stack, but this is still useful
1546 mLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
Sean Barbeauced2b2c2011-12-19 04:43:07 -05001547 mLocation.setExtras(mLocationExtras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001549 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001550 mILocationManager.reportLocation(mLocation, false);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001551 } catch (RemoteException e) {
1552 Log.e(TAG, "RemoteException calling reportLocation");
1553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 }
1555
Siddharth Raybb608c82017-03-16 11:33:34 -07001556 mGnssMetrics.logReceivedLocationStatus(hasLatLong);
1557 if (hasLatLong) {
1558 if (location.hasAccuracy()) {
1559 mGnssMetrics.logPositionAccuracyMeters(location.getAccuracy());
1560 }
1561 if (mTimeToFirstFix > 0) {
Yipeng Cao282b5942017-05-17 20:31:39 -07001562 int timeBetweenFixes = (int) (SystemClock.elapsedRealtime() - mLastFixTime);
Siddharth Raybb608c82017-03-16 11:33:34 -07001563 mGnssMetrics.logMissedReports(mFixInterval, timeBetweenFixes);
1564 }
1565 }
1566
Yipeng Cao282b5942017-05-17 20:31:39 -07001567 mLastFixTime = SystemClock.elapsedRealtime();
Hakan Gustavssonfa94ff02010-02-23 09:12:38 +01001568 // report time to first fix
Wyatt Riley5d229832017-02-10 17:06:00 -08001569 if (mTimeToFirstFix == 0 && hasLatLong) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001570 mTimeToFirstFix = (int)(mLastFixTime - mFixRequestTime);
1571 if (DEBUG) Log.d(TAG, "TTFF: " + mTimeToFirstFix);
Siddharth Raybb608c82017-03-16 11:33:34 -07001572 mGnssMetrics.logTimeToFirstFixMilliSecs(mTimeToFirstFix);
Hakan Gustavssonfa94ff02010-02-23 09:12:38 +01001573
1574 // notify status listeners
destradaaea8a8a62014-06-23 18:19:03 -07001575 mListenerHelper.onFirstFix(mTimeToFirstFix);
Hakan Gustavssonfa94ff02010-02-23 09:12:38 +01001576 }
1577
Stan Chesnutt1d72d8c2013-04-15 19:18:02 -07001578 if (mSingleShot) {
1579 stopNavigating();
1580 }
1581
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001582 if (mStarted && mStatus != LocationProvider.AVAILABLE) {
Mike Lockwoodd53ba012010-04-15 20:41:26 -04001583 // we want to time out if we do not receive a fix
Mike Lockwoodb7be5442010-02-24 14:34:50 -05001584 // within the time out and we are requesting infrequent fixes
Mike Lockwood04598b62010-04-14 17:17:24 -04001585 if (!hasCapability(GPS_CAPABILITY_SCHEDULING) && mFixInterval < NO_FIX_TIMEOUT) {
Mike Lockwoodb7be5442010-02-24 14:34:50 -05001586 mAlarmManager.cancel(mTimeoutIntent);
1587 }
1588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 // send an intent to notify that the GPS is receiving fixes.
Mike Lockwood00b74272010-03-26 10:41:48 -04001590 Intent intent = new Intent(LocationManager.GPS_FIX_CHANGE_ACTION);
1591 intent.putExtra(LocationManager.EXTRA_GPS_ENABLED, true);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001592 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001593 updateStatus(LocationProvider.AVAILABLE, mSvCount, mMeanCn0, mMaxCn0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 }
Mike Lockwood29c84342009-05-06 14:01:15 -04001595
Nick Pellyb041f232012-05-07 17:12:25 -07001596 if (!hasCapability(GPS_CAPABILITY_SCHEDULING) && mStarted &&
1597 mFixInterval > GPS_POLLING_THRESHOLD_INTERVAL) {
Mike Lockwoodd53ba012010-04-15 20:41:26 -04001598 if (DEBUG) Log.d(TAG, "got fix, hibernating");
Mike Lockwood0632ca72009-05-14 15:51:03 -04001599 hibernate();
Mike Lockwood29c84342009-05-06 14:01:15 -04001600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 }
1602
1603 /**
1604 * called from native code to update our status
1605 */
1606 private void reportStatus(int status) {
Mike Lockwoodb8d90332010-10-18 17:59:48 -04001607 if (DEBUG) Log.v(TAG, "reportStatus status: " + status);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608
destradaaea8a8a62014-06-23 18:19:03 -07001609 boolean wasNavigating = mNavigating;
1610 switch (status) {
1611 case GPS_STATUS_SESSION_BEGIN:
1612 mNavigating = true;
1613 mEngineOn = true;
1614 break;
1615 case GPS_STATUS_SESSION_END:
1616 mNavigating = false;
1617 break;
1618 case GPS_STATUS_ENGINE_ON:
1619 mEngineOn = true;
1620 break;
1621 case GPS_STATUS_ENGINE_OFF:
1622 mEngineOn = false;
1623 mNavigating = false;
1624 break;
1625 }
Mike Lockwooddbd6fd82009-12-07 18:43:36 -05001626
destradaaea8a8a62014-06-23 18:19:03 -07001627 if (wasNavigating != mNavigating) {
destradaa13a60b02015-01-15 18:36:01 -08001628 mListenerHelper.onStatusChanged(mNavigating);
Mike Lockwoodcf1d8cb2010-01-20 10:14:54 -05001629
destradaaea8a8a62014-06-23 18:19:03 -07001630 // send an intent to notify that the GPS has been enabled or disabled
1631 Intent intent = new Intent(LocationManager.GPS_ENABLED_CHANGE_ACTION);
1632 intent.putExtra(LocationManager.EXTRA_GPS_ENABLED, mNavigating);
1633 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 }
1635 }
1636
1637 /**
1638 * called from native code to update SV info
1639 */
1640 private void reportSvStatus() {
gomo4402af62017-01-11 13:20:13 -08001641 int svCount = native_read_sv_status(mSvidWithFlags,
1642 mCn0s,
1643 mSvElevations,
1644 mSvAzimuths,
1645 mSvCarrierFreqs);
destradaaea8a8a62014-06-23 18:19:03 -07001646 mListenerHelper.onSvStatusChanged(
1647 svCount,
Lifu Tang120480f2016-02-07 18:08:19 -08001648 mSvidWithFlags,
Lifu Tang76a620f2016-02-26 19:53:01 -08001649 mCn0s,
destradaaea8a8a62014-06-23 18:19:03 -07001650 mSvElevations,
gomo4402af62017-01-11 13:20:13 -08001651 mSvAzimuths,
1652 mSvCarrierFreqs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653
Siddharth Ray168f12a2017-07-10 11:55:10 -07001654 // Log CN0 as part of GNSS metrics
1655 mGnssMetrics.logCn0(mCn0s, svCount);
1656
Mike Lockwood29c84342009-05-06 14:01:15 -04001657 if (VERBOSE) {
Lifu Tang30f95a72016-01-07 23:20:38 -08001658 Log.v(TAG, "SV count: " + svCount);
1659 }
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001660 // Calculate number of satellites used in fix.
Lifu Tang30f95a72016-01-07 23:20:38 -08001661 int usedInFixCount = 0;
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001662 int maxCn0 = 0;
1663 int meanCn0 = 0;
Lifu Tang30f95a72016-01-07 23:20:38 -08001664 for (int i = 0; i < svCount; i++) {
Lifu Tang120480f2016-02-07 18:08:19 -08001665 if ((mSvidWithFlags[i] & GnssStatus.GNSS_SV_FLAGS_USED_IN_FIX) != 0) {
Lifu Tang30f95a72016-01-07 23:20:38 -08001666 ++usedInFixCount;
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001667 if (mCn0s[i] > maxCn0) {
1668 maxCn0 = (int)mCn0s[i];
1669 }
1670 meanCn0 += mCn0s[i];
Lifu Tang30f95a72016-01-07 23:20:38 -08001671 }
1672 if (VERBOSE) {
Lifu Tang120480f2016-02-07 18:08:19 -08001673 Log.v(TAG, "svid: " + (mSvidWithFlags[i] >> GnssStatus.SVID_SHIFT_WIDTH) +
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001674 " cn0: " + mCn0s[i] +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 " elev: " + mSvElevations[i] +
1676 " azimuth: " + mSvAzimuths[i] +
gomo4402af62017-01-11 13:20:13 -08001677 " carrier frequency: " + mSvCarrierFreqs[i] +
Lifu Tang120480f2016-02-07 18:08:19 -08001678 ((mSvidWithFlags[i] & GnssStatus.GNSS_SV_FLAGS_HAS_EPHEMERIS_DATA) == 0
Lifu Tang30f95a72016-01-07 23:20:38 -08001679 ? " " : " E") +
Lifu Tang120480f2016-02-07 18:08:19 -08001680 ((mSvidWithFlags[i] & GnssStatus.GNSS_SV_FLAGS_HAS_ALMANAC_DATA) == 0
Lifu Tang30f95a72016-01-07 23:20:38 -08001681 ? " " : " A") +
Lifu Tang120480f2016-02-07 18:08:19 -08001682 ((mSvidWithFlags[i] & GnssStatus.GNSS_SV_FLAGS_USED_IN_FIX) == 0
gomo4402af62017-01-11 13:20:13 -08001683 ? "" : "U") +
1684 ((mSvidWithFlags[i] & GnssStatus.GNSS_SV_FLAGS_HAS_CARRIER_FREQUENCY) == 0
1685 ? "" : "F"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 }
1687 }
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001688 if (usedInFixCount > 0) {
1689 meanCn0 /= usedInFixCount;
1690 }
1691 // return number of sats used in fix instead of total reported
1692 updateStatus(mStatus, usedInFixCount, meanCn0, maxCn0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001694 if (mNavigating && mStatus == LocationProvider.AVAILABLE && mLastFixTime > 0 &&
Yipeng Cao282b5942017-05-17 20:31:39 -07001695 SystemClock.elapsedRealtime() - mLastFixTime > RECENT_FIX_TIMEOUT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 // send an intent to notify that the GPS is no longer receiving fixes.
Mike Lockwood00b74272010-03-26 10:41:48 -04001697 Intent intent = new Intent(LocationManager.GPS_FIX_CHANGE_ACTION);
1698 intent.putExtra(LocationManager.EXTRA_GPS_ENABLED, false);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001699 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07001700 updateStatus(LocationProvider.TEMPORARILY_UNAVAILABLE, mSvCount, mMeanCn0, mMaxCn0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 }
1702 }
Mike Lockwood58bda982009-04-14 16:25:07 -04001703
1704 /**
Mike Lockwoode3635c92009-05-11 08:38:02 -04001705 * called from native code to update AGPS status
Mike Lockwood58bda982009-04-14 16:25:07 -04001706 */
destradaa96a14702014-06-05 11:36:30 -07001707 private void reportAGpsStatus(int type, int status, byte[] ipaddr) {
Mike Lockwood58bda982009-04-14 16:25:07 -04001708 switch (status) {
Mike Lockwoode3635c92009-05-11 08:38:02 -04001709 case GPS_REQUEST_AGPS_DATA_CONN:
Mike Lockwoodb6e5fa82010-10-09 20:10:46 -04001710 if (DEBUG) Log.d(TAG, "GPS_REQUEST_AGPS_DATA_CONN");
Andreas Gampee6748ce2015-12-11 18:00:38 -08001711 Log.v(TAG, "Received SUPL IP addr[]: " + Arrays.toString(ipaddr));
destradaae21252a2015-09-08 12:32:59 -07001712 InetAddress connectionIpAddress = null;
destradaa96a14702014-06-05 11:36:30 -07001713 if (ipaddr != null) {
1714 try {
destradaae21252a2015-09-08 12:32:59 -07001715 connectionIpAddress = InetAddress.getByAddress(ipaddr);
1716 if (DEBUG) Log.d(TAG, "IP address converted to: " + connectionIpAddress);
destradaa96a14702014-06-05 11:36:30 -07001717 } catch (UnknownHostException e) {
1718 Log.e(TAG, "Bad IP Address: " + ipaddr, e);
destradaa96a14702014-06-05 11:36:30 -07001719 }
1720 }
destradaae21252a2015-09-08 12:32:59 -07001721 sendMessage(REQUEST_SUPL_CONNECTION, 0 /*arg*/, connectionIpAddress);
Mike Lockwood58bda982009-04-14 16:25:07 -04001722 break;
Mike Lockwoode3635c92009-05-11 08:38:02 -04001723 case GPS_RELEASE_AGPS_DATA_CONN:
Mike Lockwoodb6e5fa82010-10-09 20:10:46 -04001724 if (DEBUG) Log.d(TAG, "GPS_RELEASE_AGPS_DATA_CONN");
destradaae21252a2015-09-08 12:32:59 -07001725 releaseSuplConnection(GPS_RELEASE_AGPS_DATA_CONN);
Mike Lockwood58bda982009-04-14 16:25:07 -04001726 break;
Mike Lockwoode3635c92009-05-11 08:38:02 -04001727 case GPS_AGPS_DATA_CONNECTED:
Mike Lockwoodb6e5fa82010-10-09 20:10:46 -04001728 if (DEBUG) Log.d(TAG, "GPS_AGPS_DATA_CONNECTED");
Mike Lockwood58bda982009-04-14 16:25:07 -04001729 break;
Mike Lockwoode3635c92009-05-11 08:38:02 -04001730 case GPS_AGPS_DATA_CONN_DONE:
Mike Lockwoodb6e5fa82010-10-09 20:10:46 -04001731 if (DEBUG) Log.d(TAG, "GPS_AGPS_DATA_CONN_DONE");
Mike Lockwood58bda982009-04-14 16:25:07 -04001732 break;
Mike Lockwoode3635c92009-05-11 08:38:02 -04001733 case GPS_AGPS_DATA_CONN_FAILED:
Mike Lockwoodb6e5fa82010-10-09 20:10:46 -04001734 if (DEBUG) Log.d(TAG, "GPS_AGPS_DATA_CONN_FAILED");
Mike Lockwood58bda982009-04-14 16:25:07 -04001735 break;
destradaa931a37f2014-08-12 16:36:59 -07001736 default:
Joe Onorato0c484102016-02-01 18:04:24 -08001737 if (DEBUG) Log.d(TAG, "Received Unknown AGPS status: " + status);
Mike Lockwood58bda982009-04-14 16:25:07 -04001738 }
1739 }
1740
destradaae21252a2015-09-08 12:32:59 -07001741 private void releaseSuplConnection(int connStatus) {
1742 sendMessage(RELEASE_SUPL_CONNECTION, connStatus, null /*obj*/);
1743 }
1744
Mike Lockwoodb16e7802009-08-06 09:26:02 -04001745 /**
1746 * called from native code to report NMEA data received
1747 */
Mike Lockwoodf602d362010-06-20 14:28:16 -07001748 private void reportNmea(long timestamp) {
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001749 if (!mItarSpeedLimitExceeded) {
1750 int length = native_read_nmea(mNmeaBuffer, mNmeaBuffer.length);
1751 String nmea = new String(mNmeaBuffer, 0 /* offset */, length);
1752 mListenerHelper.onNmeaReceived(timestamp, nmea);
1753 }
destradaaea8a8a62014-06-23 18:19:03 -07001754 }
Mike Lockwoodb16e7802009-08-06 09:26:02 -04001755
destradaaea8a8a62014-06-23 18:19:03 -07001756 /**
Wyatt Rileyaa420d52017-07-03 15:14:42 -07001757 * called from native code - GNSS measurements callback
destradaaea8a8a62014-06-23 18:19:03 -07001758 */
Lifu Tang818aa2c2016-02-01 01:52:00 -08001759 private void reportMeasurementData(GnssMeasurementsEvent event) {
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001760 if (!mItarSpeedLimitExceeded) {
Wyatt Rileyaa420d52017-07-03 15:14:42 -07001761 // send to handler to allow native to return quickly
1762 mHandler.post(new Runnable() {
1763 @Override
1764 public void run() {
1765 mGnssMeasurementsProvider.onMeasurementsAvailable(event);
1766 }
1767 });
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001768 }
Mike Lockwoodb16e7802009-08-06 09:26:02 -04001769 }
1770
Mike Lockwood62a8fc12010-03-22 14:23:26 -04001771 /**
Wyatt Rileyaa420d52017-07-03 15:14:42 -07001772 * called from native code - GNSS navigation message callback
destradaa4b3e3932014-07-21 18:01:47 -07001773 */
Lifu Tange8abe8e2016-04-01 10:32:05 -07001774 private void reportNavigationMessage(GnssNavigationMessage event) {
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001775 if (!mItarSpeedLimitExceeded) {
Wyatt Rileyaa420d52017-07-03 15:14:42 -07001776 // send to handler to allow native to return quickly
1777 mHandler.post(new Runnable() {
1778 @Override
1779 public void run() {
1780 mGnssNavigationMessageProvider.onNavigationMessageAvailable(event);
1781 }
1782 });
Wyatt Riley5d5bac82016-11-01 07:05:16 -07001783 }
destradaa4b3e3932014-07-21 18:01:47 -07001784 }
1785
1786 /**
Mike Lockwood04598b62010-04-14 17:17:24 -04001787 * called from native code to inform us what the GPS engine capabilities are
1788 */
1789 private void setEngineCapabilities(int capabilities) {
1790 mEngineCapabilities = capabilities;
Mike Lockwood9b9fb5c2011-06-29 15:09:40 -04001791
destradaa56b47f82015-07-24 10:56:18 -07001792 if (hasCapability(GPS_CAPABILITY_ON_DEMAND_TIME)) {
1793 mOnDemandTimeInjection = true;
Mike Lockwood9b9fb5c2011-06-29 15:09:40 -04001794 requestUtcTime();
1795 }
destradaa6568d702014-10-27 12:47:41 -07001796
Lifu Tang818aa2c2016-02-01 01:52:00 -08001797 mGnssMeasurementsProvider.onCapabilitiesUpdated(
destradaa6568d702014-10-27 12:47:41 -07001798 (capabilities & GPS_CAPABILITY_MEASUREMENTS) == GPS_CAPABILITY_MEASUREMENTS);
Lifu Tang818aa2c2016-02-01 01:52:00 -08001799 mGnssNavigationMessageProvider.onCapabilitiesUpdated(
destradaa6568d702014-10-27 12:47:41 -07001800 (capabilities & GPS_CAPABILITY_NAV_MESSAGES) == GPS_CAPABILITY_NAV_MESSAGES);
Mike Lockwood04598b62010-04-14 17:17:24 -04001801 }
1802
1803 /**
Lifu Tang82f893d2016-01-21 18:15:33 -08001804 * Called from native code to inform us the hardware information.
1805 */
Lifu Tang9363b942016-02-16 18:07:00 -08001806 private void setGnssYearOfHardware(int yearOfHardware) {
1807 if (DEBUG) Log.d(TAG, "setGnssYearOfHardware called with " + yearOfHardware);
Lifu Tang82f893d2016-01-21 18:15:33 -08001808 mYearOfHardware = yearOfHardware;
1809 }
1810
Lifu Tang9363b942016-02-16 18:07:00 -08001811 public interface GnssSystemInfoProvider {
Lifu Tang82f893d2016-01-21 18:15:33 -08001812 /**
1813 * Returns the year of GPS hardware.
1814 */
Lifu Tang9363b942016-02-16 18:07:00 -08001815 int getGnssYearOfHardware();
Lifu Tang82f893d2016-01-21 18:15:33 -08001816 }
1817
1818 /**
1819 * @hide
1820 */
Lifu Tang9363b942016-02-16 18:07:00 -08001821 public GnssSystemInfoProvider getGnssSystemInfoProvider() {
1822 return new GnssSystemInfoProvider() {
Lifu Tang82f893d2016-01-21 18:15:33 -08001823 @Override
Lifu Tang9363b942016-02-16 18:07:00 -08001824 public int getGnssYearOfHardware() {
Lifu Tang82f893d2016-01-21 18:15:33 -08001825 return mYearOfHardware;
1826 }
1827 };
1828 }
1829
Wyatt Rileycf879db2017-01-12 13:57:38 -08001830 public interface GnssBatchingProvider {
1831 /**
1832 * Returns the GNSS batching size
1833 */
1834 int getSize();
1835 /**
1836 * Starts the hardware batching operation
1837 */
1838 boolean start(long periodNanos, boolean wakeOnFifoFull);
1839 /**
1840 * Forces a flush of existing locations from the hardware batching
1841 */
1842 void flush();
1843 /**
1844 * Stops the batching operation
1845 */
1846 boolean stop();
1847 }
1848
1849 /**
1850 * @hide
1851 */
1852 public GnssBatchingProvider getGnssBatchingProvider() {
1853 return new GnssBatchingProvider() {
1854 @Override
1855 public int getSize() {
1856 return native_get_batch_size();
1857 }
1858 @Override
1859 public boolean start(long periodNanos, boolean wakeOnFifoFull) {
1860 if (periodNanos <= 0) {
1861 Log.e(TAG, "Invalid periodNanos " + periodNanos +
1862 "in batching request, not started");
1863 return false;
1864 }
1865 return native_start_batch(periodNanos, wakeOnFifoFull);
1866 }
1867 @Override
1868 public void flush() {
1869 native_flush_batch();
1870 }
1871 @Override
1872 public boolean stop() {
1873 return native_stop_batch();
1874 }
1875 };
1876 }
1877
Siddharth Raybb608c82017-03-16 11:33:34 -07001878 public interface GnssMetricsProvider {
1879 /**
1880 * Returns GNSS metrics as proto string
1881 */
1882 String getGnssMetricsAsProtoString();
1883 }
1884
1885 /**
1886 * @hide
1887 */
1888 public GnssMetricsProvider getGnssMetricsProvider() {
1889 return new GnssMetricsProvider() {
1890 @Override
1891 public String getGnssMetricsAsProtoString() {
1892 return mGnssMetrics.dumpGnssMetricsAsProtoString();
1893 }
1894 };
1895 }
1896
Wyatt Rileycf879db2017-01-12 13:57:38 -08001897 /**
1898 * Initialize Batching if enabled
1899 */
1900 private void enableBatching() {
1901 if (!native_init_batching()) {
1902 Log.e(TAG, "Failed to initialize GNSS batching");
1903 };
1904 }
1905
1906 /**
1907 * Disable batching
1908 */
1909 private void disableBatching() {
1910 native_stop_batch();
1911 native_cleanup_batching();
1912 }
1913
1914 /**
1915 * called from native code - GNSS location batch callback
1916 */
1917 private void reportLocationBatch(Location[] locationArray) {
1918 List<Location> locations = new ArrayList<>(Arrays.asList(locationArray));
1919 if(DEBUG) { Log.d(TAG, "Location batch of size " + locationArray.length + "reported"); }
1920 try {
1921 mILocationManager.reportLocationBatch(locations);
1922 } catch (RemoteException e) {
1923 Log.e(TAG, "RemoteException calling reportLocationBatch");
1924 }
1925 }
1926
Lifu Tang82f893d2016-01-21 18:15:33 -08001927 /**
Mike Lockwood62a8fc12010-03-22 14:23:26 -04001928 * called from native code to request XTRA data
1929 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 private void xtraDownloadRequest() {
Joe Onoratof5d95cb2010-01-07 21:48:32 -05001931 if (DEBUG) Log.d(TAG, "xtraDownloadRequest");
Mike Lockwood98e48692010-04-07 16:32:51 -04001932 sendMessage(DOWNLOAD_XTRA_DATA, 0, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 }
1934
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001935 /**
destradaa0682809a2013-08-12 18:50:30 -07001936 * Converts the GPS HAL status to the internal Geofence Hardware status.
1937 */
1938 private int getGeofenceStatus(int status) {
1939 switch(status) {
1940 case GPS_GEOFENCE_OPERATION_SUCCESS:
1941 return GeofenceHardware.GEOFENCE_SUCCESS;
1942 case GPS_GEOFENCE_ERROR_GENERIC:
1943 return GeofenceHardware.GEOFENCE_FAILURE;
1944 case GPS_GEOFENCE_ERROR_ID_EXISTS:
1945 return GeofenceHardware.GEOFENCE_ERROR_ID_EXISTS;
1946 case GPS_GEOFENCE_ERROR_INVALID_TRANSITION:
1947 return GeofenceHardware.GEOFENCE_ERROR_INVALID_TRANSITION;
1948 case GPS_GEOFENCE_ERROR_TOO_MANY_GEOFENCES:
1949 return GeofenceHardware.GEOFENCE_ERROR_TOO_MANY_GEOFENCES;
1950 case GPS_GEOFENCE_ERROR_ID_UNKNOWN:
1951 return GeofenceHardware.GEOFENCE_ERROR_ID_UNKNOWN;
1952 default:
1953 return -1;
1954 }
1955 }
1956
1957 /**
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001958 * Called from native to report GPS Geofence transition
1959 * All geofence callbacks are called on the same thread
1960 */
Wyatt Riley5d229832017-02-10 17:06:00 -08001961 private void reportGeofenceTransition(int geofenceId, Location location, int transition,
1962 long transitionTimestamp) {
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001963 if (mGeofenceHardwareImpl == null) {
1964 mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
1965 }
Wyatt Riley5d229832017-02-10 17:06:00 -08001966
destradaa0682809a2013-08-12 18:50:30 -07001967 mGeofenceHardwareImpl.reportGeofenceTransition(
1968 geofenceId,
1969 location,
1970 transition,
1971 transitionTimestamp,
1972 GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE,
1973 FusedBatchOptions.SourceTechnologies.GNSS);
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001974 }
1975
1976 /**
1977 * called from native code to report GPS status change.
1978 */
Wyatt Riley5d229832017-02-10 17:06:00 -08001979 private void reportGeofenceStatus(int status, Location location) {
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001980 if (mGeofenceHardwareImpl == null) {
1981 mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
1982 }
destradaa0682809a2013-08-12 18:50:30 -07001983 int monitorStatus = GeofenceHardware.MONITOR_CURRENTLY_UNAVAILABLE;
1984 if(status == GPS_GEOFENCE_AVAILABLE) {
1985 monitorStatus = GeofenceHardware.MONITOR_CURRENTLY_AVAILABLE;
1986 }
1987 mGeofenceHardwareImpl.reportGeofenceMonitorStatus(
1988 GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE,
1989 monitorStatus,
1990 location,
1991 FusedBatchOptions.SourceTechnologies.GNSS);
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07001992 }
1993
1994 /**
1995 * called from native code - Geofence Add callback
1996 */
1997 private void reportGeofenceAddStatus(int geofenceId, int status) {
1998 if (mGeofenceHardwareImpl == null) {
1999 mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
2000 }
destradaa0682809a2013-08-12 18:50:30 -07002001 mGeofenceHardwareImpl.reportGeofenceAddStatus(geofenceId, getGeofenceStatus(status));
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07002002 }
2003
2004 /**
2005 * called from native code - Geofence Remove callback
2006 */
2007 private void reportGeofenceRemoveStatus(int geofenceId, int status) {
2008 if (mGeofenceHardwareImpl == null) {
2009 mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
2010 }
destradaa0682809a2013-08-12 18:50:30 -07002011 mGeofenceHardwareImpl.reportGeofenceRemoveStatus(geofenceId, getGeofenceStatus(status));
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07002012 }
2013
2014 /**
2015 * called from native code - Geofence Pause callback
2016 */
2017 private void reportGeofencePauseStatus(int geofenceId, int status) {
2018 if (mGeofenceHardwareImpl == null) {
2019 mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
2020 }
destradaa0682809a2013-08-12 18:50:30 -07002021 mGeofenceHardwareImpl.reportGeofencePauseStatus(geofenceId, getGeofenceStatus(status));
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07002022 }
2023
2024 /**
2025 * called from native code - Geofence Resume callback
2026 */
2027 private void reportGeofenceResumeStatus(int geofenceId, int status) {
2028 if (mGeofenceHardwareImpl == null) {
2029 mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
2030 }
destradaa0682809a2013-08-12 18:50:30 -07002031 mGeofenceHardwareImpl.reportGeofenceResumeStatus(geofenceId, getGeofenceStatus(status));
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07002032 }
2033
Danke Xie22d1f9f2009-08-18 18:28:45 -04002034 //=============================================================
2035 // NI Client support
Miguel Torroja1e84da82010-07-27 07:02:24 +02002036 //=============================================================
Danke Xie22d1f9f2009-08-18 18:28:45 -04002037 private final INetInitiatedListener mNetInitiatedListener = new INetInitiatedListener.Stub() {
destradaaef752b62015-04-17 13:10:47 -07002038 // Sends a response for an NI request to HAL.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002039 @Override
Miguel Torroja1e84da82010-07-27 07:02:24 +02002040 public boolean sendNiResponse(int notificationId, int userResponse)
2041 {
2042 // TODO Add Permission check
Danke Xie22d1f9f2009-08-18 18:28:45 -04002043
Miguel Torroja1e84da82010-07-27 07:02:24 +02002044 if (DEBUG) Log.d(TAG, "sendNiResponse, notifId: " + notificationId +
2045 ", response: " + userResponse);
2046 native_send_ni_response(notificationId, userResponse);
2047 return true;
2048 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04002049 };
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002050
Danke Xie22d1f9f2009-08-18 18:28:45 -04002051 public INetInitiatedListener getNetInitiatedListener() {
2052 return mNetInitiatedListener;
2053 }
2054
2055 // Called by JNI function to report an NI request.
Miguel Torroja1e84da82010-07-27 07:02:24 +02002056 public void reportNiNotification(
2057 int notificationId,
2058 int niType,
2059 int notifyFlags,
2060 int timeout,
2061 int defaultResponse,
2062 String requestorId,
2063 String text,
2064 int requestorIdEncoding,
Hridya Valsaraju2ea29602016-09-13 08:38:09 -07002065 int textEncoding
Danke Xie22d1f9f2009-08-18 18:28:45 -04002066 )
Miguel Torroja1e84da82010-07-27 07:02:24 +02002067 {
2068 Log.i(TAG, "reportNiNotification: entered");
2069 Log.i(TAG, "notificationId: " + notificationId +
2070 ", niType: " + niType +
2071 ", notifyFlags: " + notifyFlags +
2072 ", timeout: " + timeout +
2073 ", defaultResponse: " + defaultResponse);
2074
2075 Log.i(TAG, "requestorId: " + requestorId +
2076 ", text: " + text +
2077 ", requestorIdEncoding: " + requestorIdEncoding +
2078 ", textEncoding: " + textEncoding);
2079
2080 GpsNiNotification notification = new GpsNiNotification();
2081
2082 notification.notificationId = notificationId;
2083 notification.niType = niType;
2084 notification.needNotify = (notifyFlags & GpsNetInitiatedHandler.GPS_NI_NEED_NOTIFY) != 0;
2085 notification.needVerify = (notifyFlags & GpsNetInitiatedHandler.GPS_NI_NEED_VERIFY) != 0;
2086 notification.privacyOverride = (notifyFlags & GpsNetInitiatedHandler.GPS_NI_PRIVACY_OVERRIDE) != 0;
2087 notification.timeout = timeout;
2088 notification.defaultResponse = defaultResponse;
2089 notification.requestorId = requestorId;
2090 notification.text = text;
2091 notification.requestorIdEncoding = requestorIdEncoding;
2092 notification.textEncoding = textEncoding;
2093
Miguel Torroja1e84da82010-07-27 07:02:24 +02002094 mNIHandler.handleNiNotification(notification);
2095 }
2096
2097 /**
2098 * Called from native code to request set id info.
2099 * We should be careful about receiving null string from the TelephonyManager,
2100 * because sending null String to JNI function would cause a crash.
2101 */
2102
2103 private void requestSetID(int flags) {
2104 TelephonyManager phone = (TelephonyManager)
2105 mContext.getSystemService(Context.TELEPHONY_SERVICE);
destradaaef752b62015-04-17 13:10:47 -07002106 int type = AGPS_SETID_TYPE_NONE;
Miguel Torroja1e84da82010-07-27 07:02:24 +02002107 String data = "";
2108
2109 if ((flags & AGPS_RIL_REQUEST_SETID_IMSI) == AGPS_RIL_REQUEST_SETID_IMSI) {
2110 String data_temp = phone.getSubscriberId();
2111 if (data_temp == null) {
2112 // This means the framework does not have the SIM card ready.
2113 } else {
2114 // This means the framework has the SIM card.
2115 data = data_temp;
2116 type = AGPS_SETID_TYPE_IMSI;
2117 }
2118 }
2119 else if ((flags & AGPS_RIL_REQUEST_SETID_MSISDN) == AGPS_RIL_REQUEST_SETID_MSISDN) {
2120 String data_temp = phone.getLine1Number();
2121 if (data_temp == null) {
2122 // This means the framework does not have the SIM card ready.
2123 } else {
2124 // This means the framework has the SIM card.
2125 data = data_temp;
2126 type = AGPS_SETID_TYPE_MSISDN;
2127 }
2128 }
2129 native_agps_set_id(type, data);
2130 }
2131
2132 /**
Mike Lockwood9b9fb5c2011-06-29 15:09:40 -04002133 * Called from native code to request utc time info
2134 */
Mike Lockwood9b9fb5c2011-06-29 15:09:40 -04002135 private void requestUtcTime() {
destradaae21252a2015-09-08 12:32:59 -07002136 if (DEBUG) Log.d(TAG, "utcTimeRequest");
Mike Lockwood9b9fb5c2011-06-29 15:09:40 -04002137 sendMessage(INJECT_NTP_TIME, 0, null);
2138 }
2139
2140 /**
Miguel Torroja1e84da82010-07-27 07:02:24 +02002141 * Called from native code to request reference location info
2142 */
2143
Hridya Valsaraju2ea29602016-09-13 08:38:09 -07002144 private void requestRefLocation() {
Miguel Torroja1e84da82010-07-27 07:02:24 +02002145 TelephonyManager phone = (TelephonyManager)
2146 mContext.getSystemService(Context.TELEPHONY_SERVICE);
Victoria Leased50d0c32012-10-29 13:16:17 -07002147 final int phoneType = phone.getPhoneType();
2148 if (phoneType == TelephonyManager.PHONE_TYPE_GSM) {
Miguel Torroja1e84da82010-07-27 07:02:24 +02002149 GsmCellLocation gsm_cell = (GsmCellLocation) phone.getCellLocation();
Victoria Leased50d0c32012-10-29 13:16:17 -07002150 if ((gsm_cell != null) && (phone.getNetworkOperator() != null)
2151 && (phone.getNetworkOperator().length() > 3)) {
Miguel Torroja1e84da82010-07-27 07:02:24 +02002152 int type;
2153 int mcc = Integer.parseInt(phone.getNetworkOperator().substring(0,3));
2154 int mnc = Integer.parseInt(phone.getNetworkOperator().substring(3));
Mike Lockwoodedc0f3872010-10-22 09:16:17 -04002155 int networkType = phone.getNetworkType();
2156 if (networkType == TelephonyManager.NETWORK_TYPE_UMTS
2157 || networkType == TelephonyManager.NETWORK_TYPE_HSDPA
2158 || networkType == TelephonyManager.NETWORK_TYPE_HSUPA
Arun Ravindran58d46122012-07-30 17:50:21 +03002159 || networkType == TelephonyManager.NETWORK_TYPE_HSPA
2160 || networkType == TelephonyManager.NETWORK_TYPE_HSPAP) {
Miguel Torroja1e84da82010-07-27 07:02:24 +02002161 type = AGPS_REF_LOCATION_TYPE_UMTS_CELLID;
Mike Lockwoodedc0f3872010-10-22 09:16:17 -04002162 } else {
Miguel Torroja1e84da82010-07-27 07:02:24 +02002163 type = AGPS_REF_LOCATION_TYPE_GSM_CELLID;
Mike Lockwoodedc0f3872010-10-22 09:16:17 -04002164 }
Miguel Torroja1e84da82010-07-27 07:02:24 +02002165 native_agps_set_ref_location_cellid(type, mcc, mnc,
2166 gsm_cell.getLac(), gsm_cell.getCid());
Mike Lockwoodedc0f3872010-10-22 09:16:17 -04002167 } else {
Miguel Torroja1e84da82010-07-27 07:02:24 +02002168 Log.e(TAG,"Error getting cell location info.");
Mike Lockwoodedc0f3872010-10-22 09:16:17 -04002169 }
Victoria Leased50d0c32012-10-29 13:16:17 -07002170 } else if (phoneType == TelephonyManager.PHONE_TYPE_CDMA) {
2171 Log.e(TAG, "CDMA not supported.");
Mike Lockwoodedc0f3872010-10-22 09:16:17 -04002172 }
Miguel Torroja1e84da82010-07-27 07:02:24 +02002173 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04002174
Mike Lockwood98e48692010-04-07 16:32:51 -04002175 private void sendMessage(int message, int arg, Object obj) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002176 // hold a wake lock until this message is delivered
Jeff Brown028872f2012-08-25 13:07:01 -07002177 // note that this assumes the message will not be removed from the queue before
2178 // it is handled (otherwise the wake lock would be leaked).
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002179 mWakeLock.acquire();
Wyatt Rileycf879db2017-01-12 13:57:38 -08002180 if (Log.isLoggable(TAG, Log.INFO)) {
2181 Log.i(TAG, "WakeLock acquired by sendMessage(" + messageIdAsString(message) + ", " + arg
2182 + ", " + obj + ")");
2183 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002184 mHandler.obtainMessage(message, arg, 1, obj).sendToTarget();
Mike Lockwood98e48692010-04-07 16:32:51 -04002185 }
2186
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002187 private final class ProviderHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08002188 public ProviderHandler(Looper looper) {
2189 super(looper, null, true /*async*/);
Jeff Brown028872f2012-08-25 13:07:01 -07002190 }
2191
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002192 @Override
Mike Lockwood4a7b65e2010-10-25 16:35:55 -04002193 public void handleMessage(Message msg) {
Mike Lockwood98e48692010-04-07 16:32:51 -04002194 int message = msg.what;
2195 switch (message) {
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002196 case ENABLE:
2197 if (msg.arg1 == 1) {
2198 handleEnable();
2199 } else {
2200 handleDisable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 }
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002202 break;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002203 case SET_REQUEST:
2204 GpsRequest gpsRequest = (GpsRequest) msg.obj;
2205 handleSetRequest(gpsRequest.request, gpsRequest.source);
Mike Lockwood03ca2162010-04-01 08:10:09 -07002206 break;
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002207 case UPDATE_NETWORK_STATE:
destradaae21252a2015-09-08 12:32:59 -07002208 handleUpdateNetworkState((Network) msg.obj);
2209 break;
2210 case REQUEST_SUPL_CONNECTION:
2211 handleRequestSuplConnection((InetAddress) msg.obj);
2212 break;
2213 case RELEASE_SUPL_CONNECTION:
2214 handleReleaseSuplConnection(msg.arg1);
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002215 break;
2216 case INJECT_NTP_TIME:
2217 handleInjectNtpTime();
2218 break;
2219 case DOWNLOAD_XTRA_DATA:
Wyatt Riley0d6e54e22016-10-05 12:03:03 -07002220 handleDownloadXtraData();
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002221 break;
Kevin Tang40e1baf2012-01-10 14:32:44 -08002222 case INJECT_NTP_TIME_FINISHED:
2223 mInjectNtpTimePending = STATE_IDLE;
2224 break;
2225 case DOWNLOAD_XTRA_DATA_FINISHED:
2226 mDownloadXtraDataPending = STATE_IDLE;
2227 break;
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002228 case UPDATE_LOCATION:
destradaae21252a2015-09-08 12:32:59 -07002229 handleUpdateLocation((Location) msg.obj);
Mike Lockwood62a8fc12010-03-22 14:23:26 -04002230 break;
destradaafb23c672015-04-16 14:01:27 -07002231 case SUBSCRIPTION_OR_SIM_CHANGED:
2232 subscriptionOrSimChanged(mContext);
2233 break;
2234 case INITIALIZE_HANDLER:
destradaae21252a2015-09-08 12:32:59 -07002235 handleInitialize();
destradaafb23c672015-04-16 14:01:27 -07002236 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002237 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002238 if (msg.arg2 == 1) {
2239 // wakelock was taken for this message, release it
2240 mWakeLock.release();
Wyatt Rileycf879db2017-01-12 13:57:38 -08002241 if (Log.isLoggable(TAG, Log.INFO)) {
2242 Log.i(TAG, "WakeLock released by handleMessage(" + messageIdAsString(message)
2243 + ", " + msg.arg1 + ", " + msg.obj + ")");
2244 }
Mike Lockwood98e48692010-04-07 16:32:51 -04002245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 }
destradaafb23c672015-04-16 14:01:27 -07002247
2248 /**
Lifu Tang30f95a72016-01-07 23:20:38 -08002249 * This method is bound to {@link #GnssLocationProvider(Context, ILocationManager, Looper)}.
destradaafb23c672015-04-16 14:01:27 -07002250 * It is in charge of loading properties and registering for events that will be posted to
2251 * this handler.
2252 */
destradaae21252a2015-09-08 12:32:59 -07002253 private void handleInitialize() {
destradaafb23c672015-04-16 14:01:27 -07002254 // load default GPS configuration
2255 // (this configuration might change in the future based on SIM changes)
2256 reloadGpsProperties(mContext, mProperties);
2257
2258 // TODO: When this object "finishes" we should unregister by invoking
2259 // SubscriptionManager.getInstance(mContext).unregister(mOnSubscriptionsChangedListener);
2260 // This is not strictly necessary because it will be unregistered if the
2261 // notification fails but it is good form.
2262
2263 // Register for SubscriptionInfo list changes which is guaranteed
2264 // to invoke onSubscriptionsChanged the first time.
2265 SubscriptionManager.from(mContext)
2266 .addOnSubscriptionsChangedListener(mOnSubscriptionsChangedListener);
2267
2268 // listen for events
destradaaef752b62015-04-17 13:10:47 -07002269 IntentFilter intentFilter;
2270 if (native_is_agps_ril_supported()) {
2271 intentFilter = new IntentFilter();
2272 intentFilter.addAction(Intents.DATA_SMS_RECEIVED_ACTION);
2273 intentFilter.addDataScheme("sms");
2274 intentFilter.addDataAuthority("localhost", "7275");
2275 mContext.registerReceiver(mBroadcastReceiver, intentFilter, null, this);
destradaafb23c672015-04-16 14:01:27 -07002276
destradaaef752b62015-04-17 13:10:47 -07002277 intentFilter = new IntentFilter();
2278 intentFilter.addAction(Intents.WAP_PUSH_RECEIVED_ACTION);
2279 try {
2280 intentFilter.addDataType("application/vnd.omaloc-supl-init");
2281 } catch (IntentFilter.MalformedMimeTypeException e) {
2282 Log.w(TAG, "Malformed SUPL init mime type");
2283 }
2284 mContext.registerReceiver(mBroadcastReceiver, intentFilter, null, this);
2285 } else if (DEBUG) {
2286 Log.d(TAG, "Skipped registration for SMS/WAP-PUSH messages because AGPS Ril in GPS"
2287 + " HAL is not supported");
destradaafb23c672015-04-16 14:01:27 -07002288 }
destradaafb23c672015-04-16 14:01:27 -07002289
2290 intentFilter = new IntentFilter();
2291 intentFilter.addAction(ALARM_WAKEUP);
2292 intentFilter.addAction(ALARM_TIMEOUT);
destradaafb23c672015-04-16 14:01:27 -07002293 intentFilter.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
Adam Lesinski87c17df2015-05-27 13:24:13 -07002294 intentFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
destradaafb23c672015-04-16 14:01:27 -07002295 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
2296 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
2297 intentFilter.addAction(SIM_STATE_CHANGED);
2298 mContext.registerReceiver(mBroadcastReceiver, intentFilter, null, this);
2299
destradaae21252a2015-09-08 12:32:59 -07002300 // register for connectivity change events, this is equivalent to the deprecated way of
2301 // registering for CONNECTIVITY_ACTION broadcasts
2302 NetworkRequest.Builder networkRequestBuilder = new NetworkRequest.Builder();
2303 networkRequestBuilder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
2304 networkRequestBuilder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
2305 NetworkRequest networkRequest = networkRequestBuilder.build();
2306 mConnMgr.registerNetworkCallback(networkRequest, mNetworkConnectivityCallback);
2307
destradaafb23c672015-04-16 14:01:27 -07002308 // listen for PASSIVE_PROVIDER updates
2309 LocationManager locManager =
2310 (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
2311 long minTime = 0;
2312 float minDistance = 0;
2313 boolean oneShot = false;
2314 LocationRequest request = LocationRequest.createFromDeprecatedProvider(
2315 LocationManager.PASSIVE_PROVIDER,
2316 minTime,
2317 minDistance,
2318 oneShot);
2319 // Don't keep track of this request since it's done on behalf of other clients
2320 // (which are kept track of separately).
2321 request.setHideFromAppOps(true);
2322 locManager.requestLocationUpdates(
2323 request,
2324 new NetworkLocationListener(),
2325 getLooper());
2326 }
2327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002329 private final class NetworkLocationListener implements LocationListener {
2330 @Override
2331 public void onLocationChanged(Location location) {
2332 // this callback happens on mHandler looper
2333 if (LocationManager.NETWORK_PROVIDER.equals(location.getProvider())) {
2334 handleUpdateLocation(location);
2335 }
2336 }
2337 @Override
2338 public void onStatusChanged(String provider, int status, Bundle extras) { }
2339 @Override
2340 public void onProviderEnabled(String provider) { }
2341 @Override
2342 public void onProviderDisabled(String provider) { }
2343 }
2344
Kevin Tanga5fe6b22011-06-05 14:25:16 -07002345 private String getSelectedApn() {
2346 Uri uri = Uri.parse("content://telephony/carriers/preferapn");
destradaa96a14702014-06-05 11:36:30 -07002347 Cursor cursor = null;
2348 try {
2349 cursor = mContext.getContentResolver().query(
2350 uri,
2351 new String[] { "apn" },
2352 null /* selection */,
2353 null /* selectionArgs */,
2354 Carriers.DEFAULT_SORT_ORDER);
2355 if (cursor != null && cursor.moveToFirst()) {
2356 return cursor.getString(0);
2357 } else {
2358 Log.e(TAG, "No APN found to select.");
2359 }
2360 } catch (Exception e) {
destradaaea8a8a62014-06-23 18:19:03 -07002361 Log.e(TAG, "Error encountered on selecting the APN.", e);
destradaa96a14702014-06-05 11:36:30 -07002362 } finally {
2363 if (cursor != null) {
Kevin Tanga5fe6b22011-06-05 14:25:16 -07002364 cursor.close();
2365 }
2366 }
destradaa96a14702014-06-05 11:36:30 -07002367
2368 return null;
2369 }
2370
2371 private int getApnIpType(String apn) {
destradaae21252a2015-09-08 12:32:59 -07002372 ensureInHandlerThread();
destradaa96a14702014-06-05 11:36:30 -07002373 if (apn == null) {
2374 return APN_INVALID;
2375 }
2376
destradaa96a14702014-06-05 11:36:30 -07002377 String selection = String.format("current = 1 and apn = '%s' and carrier_enabled = 1", apn);
2378 Cursor cursor = null;
2379 try {
2380 cursor = mContext.getContentResolver().query(
2381 Carriers.CONTENT_URI,
2382 new String[] { Carriers.PROTOCOL },
2383 selection,
2384 null,
2385 Carriers.DEFAULT_SORT_ORDER);
2386
2387 if (null != cursor && cursor.moveToFirst()) {
2388 return translateToApnIpType(cursor.getString(0), apn);
2389 } else {
2390 Log.e(TAG, "No entry found in query for APN: " + apn);
2391 }
2392 } catch (Exception e) {
2393 Log.e(TAG, "Error encountered on APN query for: " + apn, e);
2394 } finally {
2395 if (cursor != null) {
2396 cursor.close();
2397 }
2398 }
2399
2400 return APN_INVALID;
2401 }
2402
2403 private int translateToApnIpType(String ipProtocol, String apn) {
2404 if ("IP".equals(ipProtocol)) {
2405 return APN_IPV4;
2406 }
2407 if ("IPV6".equals(ipProtocol)) {
2408 return APN_IPV6;
2409 }
2410 if ("IPV4V6".equals(ipProtocol)) {
2411 return APN_IPV4V6;
2412 }
2413
2414 // we hit the default case so the ipProtocol is not recognized
2415 String message = String.format("Unknown IP Protocol: %s, for APN: %s", ipProtocol, apn);
2416 Log.e(TAG, message);
2417 return APN_INVALID;
2418 }
2419
2420 private void setRouting() {
2421 if (mAGpsDataConnectionIpAddr == null) {
2422 return;
2423 }
2424
destradaae21252a2015-09-08 12:32:59 -07002425 // TODO: replace the use of this deprecated API
destradaa96a14702014-06-05 11:36:30 -07002426 boolean result = mConnMgr.requestRouteToHostAddress(
2427 ConnectivityManager.TYPE_MOBILE_SUPL,
2428 mAGpsDataConnectionIpAddr);
2429
2430 if (!result) {
2431 Log.e(TAG, "Error requesting route to host: " + mAGpsDataConnectionIpAddr);
2432 } else if (DEBUG) {
2433 Log.d(TAG, "Successfully requested route to host: " + mAGpsDataConnectionIpAddr);
2434 }
Kevin Tanga5fe6b22011-06-05 14:25:16 -07002435 }
2436
destradaae21252a2015-09-08 12:32:59 -07002437 /**
2438 * @return {@code true} if there is a data network available for outgoing connections,
2439 * {@code false} otherwise.
2440 */
2441 private boolean isDataNetworkConnected() {
2442 NetworkInfo activeNetworkInfo = mConnMgr.getActiveNetworkInfo();
2443 return activeNetworkInfo != null && activeNetworkInfo.isConnected();
2444 }
2445
2446 /**
2447 * Ensures the calling function is running in the thread associated with {@link #mHandler}.
2448 */
2449 private void ensureInHandlerThread() {
2450 if (mHandler != null && Looper.myLooper() == mHandler.getLooper()) {
2451 return;
2452 }
2453 throw new RuntimeException("This method must run on the Handler thread.");
2454 }
2455
2456 /**
2457 * @return A string representing the current state stored in {@link #mAGpsDataConnectionState}.
2458 */
2459 private String agpsDataConnStateAsString() {
2460 switch(mAGpsDataConnectionState) {
2461 case AGPS_DATA_CONNECTION_CLOSED:
2462 return "CLOSED";
2463 case AGPS_DATA_CONNECTION_OPEN:
2464 return "OPEN";
2465 case AGPS_DATA_CONNECTION_OPENING:
2466 return "OPENING";
2467 default:
2468 return "<Unknown>";
2469 }
2470 }
2471
2472 /**
2473 * @return A string representing the given GPS_AGPS_DATA status.
2474 */
2475 private String agpsDataConnStatusAsString(int agpsDataConnStatus) {
2476 switch (agpsDataConnStatus) {
2477 case GPS_AGPS_DATA_CONNECTED:
2478 return "CONNECTED";
2479 case GPS_AGPS_DATA_CONN_DONE:
2480 return "DONE";
2481 case GPS_AGPS_DATA_CONN_FAILED:
2482 return "FAILED";
2483 case GPS_RELEASE_AGPS_DATA_CONN:
2484 return "RELEASE";
2485 case GPS_REQUEST_AGPS_DATA_CONN:
2486 return "REQUEST";
2487 default:
2488 return "<Unknown>";
2489 }
2490 }
2491
Wyatt Rileycf879db2017-01-12 13:57:38 -08002492 /**
2493 * @return A string representing the given message ID.
2494 */
2495 private String messageIdAsString(int message) {
2496 switch (message) {
2497 case ENABLE:
2498 return "ENABLE";
2499 case SET_REQUEST:
2500 return "SET_REQUEST";
2501 case UPDATE_NETWORK_STATE:
2502 return "UPDATE_NETWORK_STATE";
2503 case REQUEST_SUPL_CONNECTION:
2504 return "REQUEST_SUPL_CONNECTION";
2505 case RELEASE_SUPL_CONNECTION:
2506 return "RELEASE_SUPL_CONNECTION";
2507 case INJECT_NTP_TIME:
2508 return "INJECT_NTP_TIME";
2509 case DOWNLOAD_XTRA_DATA:
2510 return "DOWNLOAD_XTRA_DATA";
2511 case INJECT_NTP_TIME_FINISHED:
2512 return "INJECT_NTP_TIME_FINISHED";
2513 case DOWNLOAD_XTRA_DATA_FINISHED:
2514 return "DOWNLOAD_XTRA_DATA_FINISHED";
2515 case UPDATE_LOCATION:
2516 return "UPDATE_LOCATION";
2517 case SUBSCRIPTION_OR_SIM_CHANGED:
2518 return "SUBSCRIPTION_OR_SIM_CHANGED";
2519 case INITIALIZE_HANDLER:
2520 return "INITIALIZE_HANDLER";
2521 default:
2522 return "<Unknown>";
2523 }
2524 }
2525
Siddharth Raybb608c82017-03-16 11:33:34 -07002526
2527
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002528 @Override
2529 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2530 StringBuilder s = new StringBuilder();
Wyatt Riley77ca4f82017-06-30 18:13:44 -07002531 s.append(" mStarted=").append(mStarted).append('\n');
destradaa25e8caf2015-08-24 14:14:44 -07002532 s.append(" mFixInterval=").append(mFixInterval).append('\n');
2533 s.append(" mDisableGps (battery saver mode)=").append(mDisableGps).append('\n');
2534 s.append(" mEngineCapabilities=0x").append(Integer.toHexString(mEngineCapabilities));
2535 s.append(" ( ");
2536 if (hasCapability(GPS_CAPABILITY_SCHEDULING)) s.append("SCHEDULING ");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002537 if (hasCapability(GPS_CAPABILITY_MSB)) s.append("MSB ");
2538 if (hasCapability(GPS_CAPABILITY_MSA)) s.append("MSA ");
2539 if (hasCapability(GPS_CAPABILITY_SINGLE_SHOT)) s.append("SINGLE_SHOT ");
2540 if (hasCapability(GPS_CAPABILITY_ON_DEMAND_TIME)) s.append("ON_DEMAND_TIME ");
destradaa25e8caf2015-08-24 14:14:44 -07002541 if (hasCapability(GPS_CAPABILITY_GEOFENCING)) s.append("GEOFENCING ");
2542 if (hasCapability(GPS_CAPABILITY_MEASUREMENTS)) s.append("MEASUREMENTS ");
2543 if (hasCapability(GPS_CAPABILITY_NAV_MESSAGES)) s.append("NAV_MESSAGES ");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002544 s.append(")\n");
Siddharth Raybb608c82017-03-16 11:33:34 -07002545 s.append(mGnssMetrics.dumpGnssMetricsAsText());
2546 s.append(" native internal state: ").append(native_get_internal_state());
Wyatt Rileycf879db2017-01-12 13:57:38 -08002547 s.append("\n");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002548 pw.append(s);
2549 }
2550
Wei Liu6f6326b2015-06-24 23:47:50 -07002551 /**
2552 * A simple implementation of exponential backoff.
2553 */
2554 private static final class BackOff {
2555 private static final int MULTIPLIER = 2;
2556 private final long mInitIntervalMillis;
2557 private final long mMaxIntervalMillis;
2558 private long mCurrentIntervalMillis;
2559
2560 public BackOff(long initIntervalMillis, long maxIntervalMillis) {
2561 mInitIntervalMillis = initIntervalMillis;
2562 mMaxIntervalMillis = maxIntervalMillis;
2563
2564 mCurrentIntervalMillis = mInitIntervalMillis / MULTIPLIER;
2565 }
2566
2567 public long nextBackoffMillis() {
2568 if (mCurrentIntervalMillis > mMaxIntervalMillis) {
2569 return mMaxIntervalMillis;
2570 }
2571
2572 mCurrentIntervalMillis *= MULTIPLIER;
2573 return mCurrentIntervalMillis;
2574 }
2575
2576 public void reset() {
2577 mCurrentIntervalMillis = mInitIntervalMillis / MULTIPLIER;
2578 }
2579 }
2580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 // for GPS SV statistics
Lifu Tang120480f2016-02-07 18:08:19 -08002582 private static final int MAX_SVS = 64;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583
2584 // preallocated arrays, to avoid memory allocation in reportStatus()
Lifu Tang120480f2016-02-07 18:08:19 -08002585 private int mSvidWithFlags[] = new int[MAX_SVS];
Lifu Tang76a620f2016-02-26 19:53:01 -08002586 private float mCn0s[] = new float[MAX_SVS];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 private float mSvElevations[] = new float[MAX_SVS];
2588 private float mSvAzimuths[] = new float[MAX_SVS];
gomo4402af62017-01-11 13:20:13 -08002589 private float mSvCarrierFreqs[] = new float[MAX_SVS];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 private int mSvCount;
Wyatt Rileyc9f25dd2017-05-05 13:45:23 -07002591 private int mMeanCn0;
2592 private int mMaxCn0;
Mike Lockwoodb16e7802009-08-06 09:26:02 -04002593 // preallocated to avoid memory allocation in reportNmea()
2594 private byte[] mNmeaBuffer = new byte[120];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595
gomo4402af62017-01-11 13:20:13 -08002596 static { class_init_native(); }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597 private static native void class_init_native();
2598 private static native boolean native_is_supported();
destradaaef752b62015-04-17 13:10:47 -07002599 private static native boolean native_is_agps_ril_supported();
2600 private static native boolean native_is_gnss_configuration_supported();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601
2602 private native boolean native_init();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 private native void native_cleanup();
Mike Lockwood04598b62010-04-14 17:17:24 -04002604 private native boolean native_set_position_mode(int mode, int recurrence, int min_interval,
2605 int preferred_accuracy, int preferred_time);
2606 private native boolean native_start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 private native boolean native_stop();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 private native void native_delete_aiding_data(int flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 // returns number of SVs
2610 // mask[0] is ephemeris mask and mask[1] is almanac mask
Lifu Tang76a620f2016-02-26 19:53:01 -08002611 private native int native_read_sv_status(int[] prnWithFlags, float[] cn0s, float[] elevations,
gomo4402af62017-01-11 13:20:13 -08002612 float[] azimuths, float[] carrierFrequencies);
Mike Lockwoodf602d362010-06-20 14:28:16 -07002613 private native int native_read_nmea(byte[] buffer, int bufferSize);
Mike Lockwoodd26ce0d2009-06-11 12:25:46 -04002614 private native void native_inject_location(double latitude, double longitude, float accuracy);
2615
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002616 // XTRA Support
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 private native void native_inject_time(long time, long timeReference, int uncertainty);
2618 private native boolean native_supports_xtra();
2619 private native void native_inject_xtra_data(byte[] data, int length);
The Android Open Source Project10592532009-03-18 17:39:46 -07002620
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002621 // DEBUG Support
2622 private native String native_get_internal_state();
2623
2624 // AGPS Support
destradaa96a14702014-06-05 11:36:30 -07002625 private native void native_agps_data_conn_open(String apn, int apnIpType);
Mike Lockwoode3635c92009-05-11 08:38:02 -04002626 private native void native_agps_data_conn_closed();
2627 private native void native_agps_data_conn_failed();
Miguel Torroja1e84da82010-07-27 07:02:24 +02002628 private native void native_agps_ni_message(byte [] msg, int length);
Mike Lockwooda9e54612009-06-19 14:54:42 -04002629 private native void native_set_agps_server(int type, String hostname, int port);
Danke Xie22d1f9f2009-08-18 18:28:45 -04002630
2631 // Network-initiated (NI) Support
2632 private native void native_send_ni_response(int notificationId, int userResponse);
Miguel Torroja1e84da82010-07-27 07:02:24 +02002633
2634 // AGPS ril suport
2635 private native void native_agps_set_ref_location_cellid(int type, int mcc, int mnc,
2636 int lac, int cid);
2637 private native void native_agps_set_id(int type, String setid);
Mike Lockwood50130bb2010-10-11 06:22:50 -04002638
2639 private native void native_update_network_state(boolean connected, int type,
Kevin Tanga5fe6b22011-06-05 14:25:16 -07002640 boolean roaming, boolean available, String extraInfo, String defaultAPN);
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -07002641
2642 // Hardware Geofence support.
2643 private static native boolean native_is_geofence_supported();
2644 private static native boolean native_add_geofence(int geofenceId, double latitude,
2645 double longitude, double radius, int lastTransition,int monitorTransitions,
2646 int notificationResponsivenes, int unknownTimer);
2647 private static native boolean native_remove_geofence(int geofenceId);
2648 private static native boolean native_resume_geofence(int geofenceId, int transitions);
2649 private static native boolean native_pause_geofence(int geofenceId);
destradaaea8a8a62014-06-23 18:19:03 -07002650
2651 // Gps Hal measurements support.
2652 private static native boolean native_is_measurement_supported();
destradaa4b3e3932014-07-21 18:01:47 -07002653 private native boolean native_start_measurement_collection();
2654 private native boolean native_stop_measurement_collection();
2655
2656 // Gps Navigation message support.
2657 private static native boolean native_is_navigation_message_supported();
2658 private native boolean native_start_navigation_message_collection();
2659 private native boolean native_stop_navigation_message_collection();
Tsuwei Chen52617bb2014-08-25 11:49:11 -07002660
2661 // GNSS Configuration
Hridya Valsaraju2ea29602016-09-13 08:38:09 -07002662 private static native boolean native_set_supl_version(int version);
2663 private static native boolean native_set_supl_mode(int mode);
2664 private static native boolean native_set_supl_es(int es);
2665 private static native boolean native_set_lpp_profile(int lppProfile);
2666 private static native boolean native_set_gnss_pos_protocol_select(int gnssPosProtocolSelect);
2667 private static native boolean native_set_gps_lock(int gpsLock);
2668 private static native boolean native_set_emergency_supl_pdn(int emergencySuplPdn);
2669
Wyatt Rileycf879db2017-01-12 13:57:38 -08002670 // GNSS Batching
2671 private static native int native_get_batch_size();
2672 private static native boolean native_start_batch(long periodNanos, boolean wakeOnFifoFull);
2673 private static native void native_flush_batch();
2674 private static native boolean native_stop_batch();
2675 private static native boolean native_init_batching();
2676 private static native void native_cleanup_batching();
2677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678}