1 /* 2 * Copyright (C) 2017 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 17 package android.telephony; 18 19 import static com.android.internal.util.Preconditions.checkNotNull; 20 21 import android.annotation.Nullable; 22 import android.annotation.RequiresFeature; 23 import android.content.pm.PackageManager; 24 import android.os.Binder; 25 import android.os.Bundle; 26 import android.os.Handler; 27 import android.os.HandlerThread; 28 import android.os.Looper; 29 import android.os.Message; 30 import android.os.Messenger; 31 import android.os.Parcelable; 32 import android.os.RemoteException; 33 import android.util.SparseArray; 34 35 import com.android.internal.annotations.GuardedBy; 36 import com.android.internal.telephony.ITelephony; 37 import com.android.telephony.Rlog; 38 39 import java.util.Arrays; 40 import java.util.List; 41 import java.util.Objects; 42 import java.util.concurrent.Executor; 43 44 /** 45 * Manages the radio access network scan requests and callbacks. 46 */ 47 @RequiresFeature(PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS) 48 public final class TelephonyScanManager { 49 50 private static final String TAG = "TelephonyScanManager"; 51 52 /** @hide */ 53 public static final String SCAN_RESULT_KEY = "scanResult"; 54 55 /** @hide */ 56 public static final int CALLBACK_SCAN_RESULTS = 1; 57 /** @hide */ 58 public static final int CALLBACK_SCAN_ERROR = 2; 59 /** @hide */ 60 public static final int CALLBACK_SCAN_COMPLETE = 3; 61 /** @hide */ 62 public static final int CALLBACK_RESTRICTED_SCAN_RESULTS = 4; 63 /** @hide */ 64 public static final int CALLBACK_TELEPHONY_DIED = 5; 65 66 /** @hide */ 67 public static final int INVALID_SCAN_ID = -1; 68 69 /** 70 * The caller of 71 * {@link 72 * TelephonyManager#requestNetworkScan(NetworkScanRequest, Executor, NetworkScanCallback)} 73 * should implement and provide this callback so that the scan results or errors can be 74 * returned. 75 */ 76 public static abstract class NetworkScanCallback { 77 /** Returns the scan results to the user, this callback will be called multiple times. */ onResults(List<CellInfo> results)78 public void onResults(List<CellInfo> results) {} 79 80 /** 81 * Informs the user that the scan has stopped. 82 * 83 * This callback will be called when the scan is finished or cancelled by the user. 84 * The related NetworkScanRequest will be deleted after this callback. 85 */ onComplete()86 public void onComplete() {} 87 88 /** 89 * Informs the user that there is some error about the scan. 90 * 91 * This callback will be called whenever there is any error about the scan, and the scan 92 * will be terminated. onComplete() will NOT be called. 93 * 94 * @param error Error code when the scan is failed, as defined in {@link NetworkScan}. 95 */ onError(@etworkScan.ScanErrorCode int error)96 public void onError(@NetworkScan.ScanErrorCode int error) {} 97 } 98 99 private static class NetworkScanInfo { 100 private final NetworkScanRequest mRequest; 101 private final Executor mExecutor; 102 private final NetworkScanCallback mCallback; 103 NetworkScanInfo( NetworkScanRequest request, Executor executor, NetworkScanCallback callback)104 NetworkScanInfo( 105 NetworkScanRequest request, Executor executor, NetworkScanCallback callback) { 106 mRequest = request; 107 mExecutor = executor; 108 mCallback = callback; 109 } 110 } 111 112 private final Looper mLooper; 113 private final Handler mHandler; 114 private final Messenger mMessenger; 115 private final SparseArray<NetworkScanInfo> mScanInfo = new SparseArray<NetworkScanInfo>(); 116 private final Binder.DeathRecipient mDeathRecipient; 117 TelephonyScanManager()118 public TelephonyScanManager() { 119 HandlerThread thread = new HandlerThread(TAG); 120 thread.start(); 121 mLooper = thread.getLooper(); 122 mHandler = new Handler(mLooper) { 123 @Override 124 public void handleMessage(Message message) { 125 checkNotNull(message, "message cannot be null"); 126 if (message.what == CALLBACK_TELEPHONY_DIED) { 127 // If there are no objects in mScanInfo then binder death will simply return. 128 synchronized (mScanInfo) { 129 for (int i = 0; i < mScanInfo.size(); i++) { 130 NetworkScanInfo nsi = mScanInfo.valueAt(i); 131 // At this point we go into panic mode and ignore errors that would 132 // normally stop the show in order to try and clean up as gracefully 133 // as possible. 134 if (nsi == null) continue; // shouldn't be possible 135 Executor e = nsi.mExecutor; 136 NetworkScanCallback cb = nsi.mCallback; 137 if (e == null || cb == null) continue; 138 try { 139 e.execute( 140 () -> cb.onError(NetworkScan.ERROR_MODEM_UNAVAILABLE)); 141 } catch (java.util.concurrent.RejectedExecutionException ignore) { 142 // ignore so that we can continue 143 } 144 } 145 146 mScanInfo.clear(); 147 } 148 return; 149 } 150 151 NetworkScanInfo nsi; 152 synchronized (mScanInfo) { 153 nsi = mScanInfo.get(message.arg2); 154 } 155 if (nsi == null) { 156 throw new RuntimeException( 157 "Failed to find NetworkScanInfo with id " + message.arg2); 158 } 159 160 final NetworkScanCallback callback = nsi.mCallback; 161 final Executor executor = nsi.mExecutor; 162 163 switch (message.what) { 164 case CALLBACK_RESTRICTED_SCAN_RESULTS: 165 case CALLBACK_SCAN_RESULTS: 166 try { 167 final Bundle b = message.getData(); 168 final Parcelable[] parcelables = b.getParcelableArray(SCAN_RESULT_KEY); 169 CellInfo[] ci = new CellInfo[parcelables.length]; 170 for (int i = 0; i < parcelables.length; i++) { 171 ci[i] = (CellInfo) parcelables[i]; 172 } 173 executor.execute(() -> { 174 Rlog.d(TAG, "onResults: " + ci.toString()); 175 callback.onResults(Arrays.asList(ci)); 176 }); 177 } catch (Exception e) { 178 Rlog.e(TAG, "Exception in networkscan callback onResults", e); 179 } 180 break; 181 case CALLBACK_SCAN_ERROR: 182 try { 183 final int errorCode = message.arg1; 184 executor.execute(() -> { 185 Rlog.d(TAG, "onError: " + errorCode); 186 callback.onError(errorCode); 187 }); 188 synchronized (mScanInfo) { 189 mScanInfo.remove(message.arg2); 190 } 191 } catch (Exception e) { 192 Rlog.e(TAG, "Exception in networkscan callback onError", e); 193 } 194 break; 195 case CALLBACK_SCAN_COMPLETE: 196 try { 197 executor.execute(() -> { 198 Rlog.d(TAG, "onComplete"); 199 callback.onComplete(); 200 }); 201 synchronized (mScanInfo) { 202 mScanInfo.remove(message.arg2); 203 } 204 } catch (Exception e) { 205 Rlog.e(TAG, "Exception in networkscan callback onComplete", e); 206 } 207 break; 208 default: 209 Rlog.e(TAG, "Unhandled message " + Integer.toHexString(message.what)); 210 break; 211 } 212 } 213 }; 214 mMessenger = new Messenger(mHandler); 215 mDeathRecipient = new Binder.DeathRecipient() { 216 @Override 217 public void binderDied() { 218 mHandler.obtainMessage(CALLBACK_TELEPHONY_DIED).sendToTarget(); 219 } 220 }; 221 } 222 223 /** 224 * Request a network scan. 225 * 226 * This method is asynchronous, so the network scan results will be returned by callback. 227 * The returned NetworkScan will contain a callback method which can be used to stop the scan. 228 * 229 * <p> 230 * Requires Permission: 231 * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} and 232 * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE} 233 * Or the calling app has carrier privileges. @see #hasCarrierPrivileges 234 * @param renounceFineLocationAccess Set this to true if the caller would not like to receive 235 * location related information which will be sent if the caller already possess 236 * {@link android.Manifest.permission.ACCESS_FINE_LOCATION} and do not renounce the permission 237 * @param request Contains all the RAT with bands/channels that need to be scanned. 238 * @param callback Returns network scan results or errors. 239 * @param callingPackage The package name of the caller 240 * @param callingFeatureId The feature id inside of the calling package 241 * @return A NetworkScan obj which contains a callback which can stop the scan. 242 * @hide 243 */ requestNetworkScan(int subId, boolean renounceFineLocationAccess, NetworkScanRequest request, Executor executor, NetworkScanCallback callback, String callingPackage, @Nullable String callingFeatureId)244 public NetworkScan requestNetworkScan(int subId, 245 boolean renounceFineLocationAccess, 246 NetworkScanRequest request, Executor executor, NetworkScanCallback callback, 247 String callingPackage, @Nullable String callingFeatureId) { 248 try { 249 Objects.requireNonNull(request, "Request was null"); 250 Objects.requireNonNull(callback, "Callback was null"); 251 Objects.requireNonNull(executor, "Executor was null"); 252 final ITelephony telephony = getITelephony(); 253 if (telephony == null) return null; 254 255 // The lock must be taken before calling requestNetworkScan because the resulting 256 // scanId can be invoked asynchronously on another thread at any time after 257 // requestNetworkScan invoked, leaving a critical section between that call and adding 258 // the record to the ScanInfo cache. 259 synchronized (mScanInfo) { 260 int scanId = telephony.requestNetworkScan( 261 subId, renounceFineLocationAccess, request, mMessenger, 262 new Binder(), callingPackage, 263 callingFeatureId); 264 if (scanId == INVALID_SCAN_ID) { 265 Rlog.e(TAG, "Failed to initiate network scan"); 266 return null; 267 } 268 // We link to death whenever a scan is started to ensure that we are linked 269 // at the point that phone process death might matter. 270 // We never unlink because: 271 // - Duplicate links to death with the same callback do not result in 272 // extraneous callbacks (the tracking de-dupes). 273 // - Receiving binderDeath() when no scans are active is a no-op. 274 telephony.asBinder().linkToDeath(mDeathRecipient, 0); 275 saveScanInfo(scanId, request, executor, callback); 276 return new NetworkScan(scanId, subId); 277 } 278 } catch (RemoteException ex) { 279 Rlog.e(TAG, "requestNetworkScan RemoteException", ex); 280 } catch (NullPointerException ex) { 281 Rlog.e(TAG, "requestNetworkScan NPE", ex); 282 } 283 return null; 284 } 285 286 @GuardedBy("mScanInfo") saveScanInfo( int id, NetworkScanRequest request, Executor executor, NetworkScanCallback callback)287 private void saveScanInfo( 288 int id, NetworkScanRequest request, Executor executor, NetworkScanCallback callback) { 289 mScanInfo.put(id, new NetworkScanInfo(request, executor, callback)); 290 } 291 getITelephony()292 private ITelephony getITelephony() { 293 return ITelephony.Stub.asInterface( 294 TelephonyFrameworkInitializer 295 .getTelephonyServiceManager() 296 .getTelephonyServiceRegisterer() 297 .get()); 298 } 299 } 300