NetworkScoreManager.java revision 972e236e84fd4073f7ecc40f2de326b388203dfb
1/* 2 * Copyright (C) 2014 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 17package android.net; 18 19import android.Manifest; 20import android.annotation.SdkConstant; 21import android.annotation.SdkConstant.SdkConstantType; 22import android.annotation.SystemApi; 23import android.content.Context; 24import android.content.Intent; 25import android.net.NetworkScorerAppManager.NetworkScorerAppData; 26import android.os.IBinder; 27import android.os.RemoteException; 28import android.os.ServiceManager; 29import android.os.UserHandle; 30 31/** 32 * Class that manages communication between network subsystems and a network scorer. 33 * 34 * <p>You can get an instance of this class by calling 35 * {@link android.content.Context#getSystemService(String)}: 36 * 37 * <pre>NetworkScoreManager manager = 38 * (NetworkScoreManager) getSystemService(Context.NETWORK_SCORE_SERVICE)</pre> 39 * 40 * <p>A network scorer is any application which: 41 * <ul> 42 * <li>Declares the {@link android.Manifest.permission#SCORE_NETWORKS} permission. 43 * <li>Includes a receiver for {@link #ACTION_SCORE_NETWORKS} guarded by the 44 * {@link android.Manifest.permission#BROADCAST_NETWORK_PRIVILEGED} permission which scores 45 * networks and (eventually) calls {@link #updateScores} with the results. If this receiver 46 * specifies an android:label attribute, this label will be used when referring to the 47 * application throughout system settings; otherwise, the application label will be used. 48 * </ul> 49 * 50 * <p>The system keeps track of an active scorer application; at any time, only this application 51 * will receive {@link #ACTION_SCORE_NETWORKS} broadcasts and will be permitted to call 52 * {@link #updateScores}. Applications may determine the current active scorer with 53 * {@link #getActiveScorerPackage()} and request to change the active scorer by sending an 54 * {@link #ACTION_CHANGE_ACTIVE} broadcast with another scorer. 55 * 56 * @hide 57 */ 58@SystemApi 59public class NetworkScoreManager { 60 /** 61 * Activity action: ask the user to change the active network scorer. This will show a dialog 62 * that asks the user whether they want to replace the current active scorer with the one 63 * specified in {@link #EXTRA_PACKAGE_NAME}. The activity will finish with RESULT_OK if the 64 * active scorer was changed or RESULT_CANCELED if it failed for any reason. 65 */ 66 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 67 public static final String ACTION_CHANGE_ACTIVE = "android.net.scoring.CHANGE_ACTIVE"; 68 69 /** 70 * Extra used with {@link #ACTION_CHANGE_ACTIVE} to specify the new scorer package. Set with 71 * {@link android.content.Intent#putExtra(String, String)}. 72 */ 73 public static final String EXTRA_PACKAGE_NAME = "packageName"; 74 75 /** 76 * Broadcast action: new network scores are being requested. This intent will only be delivered 77 * to the current active scorer app. That app is responsible for scoring the networks and 78 * calling {@link #updateScores} when complete. The networks to score are specified in 79 * {@link #EXTRA_NETWORKS_TO_SCORE}, and will generally consist of all networks which have been 80 * configured by the user as well as any open networks. 81 * 82 * <p class="note">This is a protected intent that can only be sent by the system. 83 */ 84 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 85 public static final String ACTION_SCORE_NETWORKS = "android.net.scoring.SCORE_NETWORKS"; 86 87 /** 88 * Extra used with {@link #ACTION_SCORE_NETWORKS} to specify the networks to be scored, as an 89 * array of {@link NetworkKey}s. Can be obtained with 90 * {@link android.content.Intent#getParcelableArrayExtra(String)}}. 91 */ 92 public static final String EXTRA_NETWORKS_TO_SCORE = "networksToScore"; 93 94 /** 95 * Activity action: launch a custom activity for configuring a scorer before enabling it. 96 * Scorer applications may choose to specify an activity for this action, in which case the 97 * framework will launch that activity which should return RESULT_OK if scoring was enabled. 98 * 99 * <p>If no activity is included in a scorer which implements this action, the system dialog for 100 * selecting a scorer will be shown instead. 101 */ 102 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) 103 public static final String ACTION_CUSTOM_ENABLE = "android.net.scoring.CUSTOM_ENABLE"; 104 105 /** 106 * Broadcast action: the active scorer has been changed. Scorer apps may listen to this to 107 * perform initialization once selected as the active scorer, or clean up unneeded resources 108 * if another scorer has been selected. This is an explicit broadcast only sent to the 109 * previous scorer and new scorer. Note that it is unnecessary to clear existing scores as 110 * this is handled by the system. 111 * 112 * <p>The new scorer will be specified in {@link #EXTRA_NEW_SCORER}. 113 * 114 * <p class="note">This is a protected intent that can only be sent by the system. 115 */ 116 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 117 public static final String ACTION_SCORER_CHANGED = "android.net.scoring.SCORER_CHANGED"; 118 119 /** 120 * Service action: Used to discover and bind to a network recommendation provider. 121 * Implementations should return {@link NetworkRecommendationProvider#getBinder()} from 122 * their <code>onBind()</code> method. 123 */ 124 @SdkConstant(SdkConstantType.SERVICE_ACTION) 125 public static final String ACTION_RECOMMEND_NETWORKS = "android.net.action.RECOMMEND_NETWORKS"; 126 127 /** 128 * Extra used with {@link #ACTION_SCORER_CHANGED} to specify the newly selected scorer's package 129 * name. Will be null if scoring was disabled. Can be obtained with 130 * {@link android.content.Intent#getStringExtra(String)}. 131 */ 132 public static final String EXTRA_NEW_SCORER = "newScorer"; 133 134 private final Context mContext; 135 private final INetworkScoreService mService; 136 137 /** @hide */ 138 public NetworkScoreManager(Context context) { 139 mContext = context; 140 IBinder iBinder = ServiceManager.getService(Context.NETWORK_SCORE_SERVICE); 141 mService = INetworkScoreService.Stub.asInterface(iBinder); 142 } 143 144 /** 145 * Obtain the package name of the current active network scorer. 146 * 147 * <p>At any time, only one scorer application will receive {@link #ACTION_SCORE_NETWORKS} 148 * broadcasts and be allowed to call {@link #updateScores}. Applications may use this method to 149 * determine the current scorer and offer the user the ability to select a different scorer via 150 * the {@link #ACTION_CHANGE_ACTIVE} intent. 151 * @return the full package name of the current active scorer, or null if there is no active 152 * scorer. 153 */ 154 public String getActiveScorerPackage() { 155 NetworkScorerAppData app = new NetworkScorerAppManager(mContext).getActiveScorer(); 156 if (app == null) { 157 return null; 158 } 159 return app.mPackageName; 160 } 161 162 /** 163 * Update network scores. 164 * 165 * <p>This may be called at any time to re-score active networks. Scores will generally be 166 * updated quickly, but if this method is called too frequently, the scores may be held and 167 * applied at a later time. 168 * 169 * @param networks the networks which have been scored by the scorer. 170 * @return whether the update was successful. 171 * @throws SecurityException if the caller is not the active scorer. 172 */ 173 public boolean updateScores(ScoredNetwork[] networks) throws SecurityException { 174 try { 175 return mService.updateScores(networks); 176 } catch (RemoteException e) { 177 throw e.rethrowFromSystemServer(); 178 } 179 } 180 181 /** 182 * Clear network scores. 183 * 184 * <p>Should be called when all scores need to be invalidated, i.e. because the scoring 185 * algorithm has changed and old scores can no longer be compared to future scores. 186 * 187 * <p>Note that scores will be cleared automatically when the active scorer changes, as scores 188 * from one scorer cannot be compared to those from another scorer. 189 * 190 * @return whether the clear was successful. 191 * @throws SecurityException if the caller is not the active scorer or privileged. 192 */ 193 public boolean clearScores() throws SecurityException { 194 try { 195 return mService.clearScores(); 196 } catch (RemoteException e) { 197 throw e.rethrowFromSystemServer(); 198 } 199 } 200 201 /** 202 * Set the active scorer to a new package and clear existing scores. 203 * 204 * <p>Should never be called directly without obtaining user consent. This can be done by using 205 * the {@link #ACTION_CHANGE_ACTIVE} broadcast, or using a custom configuration activity. 206 * 207 * @return true if the operation succeeded, or false if the new package is not a valid scorer. 208 * @throws SecurityException if the caller does not hold the 209 * {@link android.Manifest.permission#SCORE_NETWORKS} permission. 210 * @hide 211 */ 212 @SystemApi 213 public boolean setActiveScorer(String packageName) throws SecurityException { 214 try { 215 return mService.setActiveScorer(packageName); 216 } catch (RemoteException e) { 217 throw e.rethrowFromSystemServer(); 218 } 219 } 220 221 /** 222 * Turn off network scoring. 223 * 224 * <p>May only be called by the current scorer app, or the system. 225 * 226 * @throws SecurityException if the caller is neither the active scorer nor the system. 227 */ 228 public void disableScoring() throws SecurityException { 229 try { 230 mService.disableScoring(); 231 } catch (RemoteException e) { 232 throw e.rethrowFromSystemServer(); 233 } 234 } 235 236 /** 237 * Request scoring for networks. 238 * 239 * <p>Note that this is just a helper method to assemble the broadcast, and will run in the 240 * calling process. 241 * 242 * @return true if the broadcast was sent, or false if there is no active scorer. 243 * @throws SecurityException if the caller does not hold the 244 * {@link android.Manifest.permission#BROADCAST_NETWORK_PRIVILEGED} permission. 245 * @hide 246 */ 247 public boolean requestScores(NetworkKey[] networks) throws SecurityException { 248 String activeScorer = getActiveScorerPackage(); 249 if (activeScorer == null) { 250 return false; 251 } 252 Intent intent = new Intent(ACTION_SCORE_NETWORKS); 253 intent.setPackage(activeScorer); 254 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 255 intent.putExtra(EXTRA_NETWORKS_TO_SCORE, networks); 256 // A scorer should never become active if its package doesn't hold SCORE_NETWORKS, but 257 // ensure the package still holds it to be extra safe. 258 // TODO: http://b/23422763 259 mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM, Manifest.permission.SCORE_NETWORKS); 260 return true; 261 } 262 263 /** 264 * Register a network score cache. 265 * 266 * @param networkType the type of network this cache can handle. See {@link NetworkKey#type}. 267 * @param scoreCache implementation of {@link INetworkScoreCache} to store the scores. 268 * @throws SecurityException if the caller does not hold the 269 * {@link android.Manifest.permission#BROADCAST_NETWORK_PRIVILEGED} permission. 270 * @throws IllegalArgumentException if a score cache is already registered for this type. 271 * @hide 272 */ 273 public void registerNetworkScoreCache(int networkType, INetworkScoreCache scoreCache) { 274 try { 275 mService.registerNetworkScoreCache(networkType, scoreCache); 276 } catch (RemoteException e) { 277 throw e.rethrowFromSystemServer(); 278 } 279 } 280 281 /** 282 * Unregister a network score cache. 283 * 284 * @param networkType the type of network this cache can handle. See {@link NetworkKey#type}. 285 * @param scoreCache implementation of {@link INetworkScoreCache} to store the scores. 286 * @throws SecurityException if the caller does not hold the 287 * {@link android.Manifest.permission#BROADCAST_NETWORK_PRIVILEGED} permission. 288 * @throws IllegalArgumentException if a score cache is already registered for this type. 289 * @hide 290 */ 291 public void unregisterNetworkScoreCache(int networkType, INetworkScoreCache scoreCache) { 292 try { 293 mService.unregisterNetworkScoreCache(networkType, scoreCache); 294 } catch (RemoteException e) { 295 throw e.rethrowFromSystemServer(); 296 } 297 } 298 299 /** 300 * Request a recommendation for which network to connect to. 301 * 302 * @param request a {@link RecommendationRequest} instance containing additional 303 * request details 304 * @return a {@link RecommendationResult} instance containing the recommended network 305 * to connect to 306 * @throws SecurityException 307 */ 308 public RecommendationResult requestRecommendation(RecommendationRequest request) 309 throws SecurityException { 310 try { 311 return mService.requestRecommendation(request); 312 } catch (RemoteException e) { 313 throw e.rethrowFromSystemServer(); 314 } 315 } 316} 317