MobileDataStateTracker.java revision a22ae073cc727eb4cf2c6734d6ba7336d6d9e2b4
1/* 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 17package android.net; 18 19import android.content.BroadcastReceiver; 20import android.content.Context; 21import android.content.Intent; 22import android.content.IntentFilter; 23import android.os.RemoteException; 24import android.os.Handler; 25import android.os.ServiceManager; 26import android.os.SystemProperties; 27import com.android.internal.telephony.ITelephony; 28import com.android.internal.telephony.Phone; 29import com.android.internal.telephony.TelephonyIntents; 30import android.net.NetworkInfo.DetailedState; 31import android.telephony.TelephonyManager; 32import android.util.Log; 33import android.text.TextUtils; 34 35/** 36 * Track the state of mobile data connectivity. This is done by 37 * receiving broadcast intents from the Phone process whenever 38 * the state of data connectivity changes. 39 * 40 * {@hide} 41 */ 42public class MobileDataStateTracker extends NetworkStateTracker { 43 44 private static final String TAG = "MobileDataStateTracker"; 45 private static final boolean DBG = true; 46 47 private Phone.DataState mMobileDataState; 48 private ITelephony mPhoneService; 49 50 private String mApnType; 51 private String mApnTypeToWatchFor; 52 private String mApnName; 53 private boolean mEnabled; 54 private BroadcastReceiver mStateReceiver; 55 56 // DEFAULT and HIPRI are the same connection. If we're one of these we need to check if 57 // the other is also disconnected before we reset sockets 58 private boolean mIsDefaultOrHipri = false; 59 60 /** 61 * Create a new MobileDataStateTracker 62 * @param context the application context of the caller 63 * @param target a message handler for getting callbacks about state changes 64 * @param netType the ConnectivityManager network type 65 * @param apnType the Phone apnType 66 * @param tag the name of this network 67 */ 68 public MobileDataStateTracker(Context context, Handler target, int netType, String tag) { 69 super(context, target, netType, 70 TelephonyManager.getDefault().getNetworkType(), tag, 71 TelephonyManager.getDefault().getNetworkTypeName()); 72 mApnType = networkTypeToApnType(netType); 73 if (TextUtils.equals(mApnType, Phone.APN_TYPE_HIPRI)) { 74 mApnTypeToWatchFor = Phone.APN_TYPE_DEFAULT; 75 } else { 76 mApnTypeToWatchFor = mApnType; 77 } 78 if (netType == ConnectivityManager.TYPE_MOBILE || 79 netType == ConnectivityManager.TYPE_MOBILE_HIPRI) { 80 mIsDefaultOrHipri = true; 81 } 82 83 mPhoneService = null; 84 if(netType == ConnectivityManager.TYPE_MOBILE) { 85 mEnabled = true; 86 } else { 87 mEnabled = false; 88 } 89 90 mDnsPropNames = new String[] { 91 "net.rmnet0.dns1", 92 "net.rmnet0.dns2", 93 "net.eth0.dns1", 94 "net.eth0.dns2", 95 "net.eth0.dns3", 96 "net.eth0.dns4", 97 "net.gprs.dns1", 98 "net.gprs.dns2", 99 "net.ppp0.dns1", 100 "net.ppp0.dns2"}; 101 102 } 103 104 /** 105 * Begin monitoring mobile data connectivity. 106 */ 107 public void startMonitoring() { 108 IntentFilter filter = 109 new IntentFilter(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED); 110 filter.addAction(TelephonyIntents.ACTION_DATA_CONNECTION_FAILED); 111 filter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED); 112 113 mStateReceiver = new MobileDataStateReceiver(); 114 Intent intent = mContext.registerReceiver(mStateReceiver, filter); 115 if (intent != null) 116 mMobileDataState = getMobileDataState(intent); 117 else 118 mMobileDataState = Phone.DataState.DISCONNECTED; 119 } 120 121 private Phone.DataState getMobileDataState(Intent intent) { 122 String str = intent.getStringExtra(Phone.STATE_KEY); 123 if (str != null) { 124 String apnTypeList = 125 intent.getStringExtra(Phone.DATA_APN_TYPES_KEY); 126 if (isApnTypeIncluded(apnTypeList)) { 127 return Enum.valueOf(Phone.DataState.class, str); 128 } 129 } 130 return Phone.DataState.DISCONNECTED; 131 } 132 133 private boolean isApnTypeIncluded(String typeList) { 134 /* comma seperated list - split and check */ 135 if (typeList == null) 136 return false; 137 138 String[] list = typeList.split(","); 139 for(int i=0; i< list.length; i++) { 140 if (TextUtils.equals(list[i], mApnTypeToWatchFor) || 141 TextUtils.equals(list[i], Phone.APN_TYPE_ALL)) { 142 return true; 143 } 144 } 145 return false; 146 } 147 148 private class MobileDataStateReceiver extends BroadcastReceiver { 149 ConnectivityManager mConnectivityManager; 150 public void onReceive(Context context, Intent intent) { 151 synchronized(this) { 152 if (intent.getAction().equals(TelephonyIntents. 153 ACTION_ANY_DATA_CONNECTION_STATE_CHANGED)) { 154 Phone.DataState state = getMobileDataState(intent); 155 String reason = intent.getStringExtra(Phone.STATE_CHANGE_REASON_KEY); 156 String apnName = intent.getStringExtra(Phone.DATA_APN_KEY); 157 String apnTypeList = intent.getStringExtra(Phone.DATA_APN_TYPES_KEY); 158 mApnName = apnName; 159 160 boolean unavailable = intent.getBooleanExtra(Phone.NETWORK_UNAVAILABLE_KEY, 161 false); 162 163 // set this regardless of the apnTypeList. It's all the same radio/network 164 // underneath 165 mNetworkInfo.setIsAvailable(!unavailable); 166 167 if (isApnTypeIncluded(apnTypeList)) { 168 if (mEnabled == false) { 169 // if we're not enabled but the APN Type is supported by this connection 170 // we should record the interface name if one's provided. If the user 171 // turns on this network we will need the interfacename but won't get 172 // a fresh connected message - TODO fix this when we get per-APN 173 // notifications 174 if (state == Phone.DataState.CONNECTED) { 175 if (DBG) Log.d(TAG, "replacing old mInterfaceName (" + 176 mInterfaceName + ") with " + 177 intent.getStringExtra(Phone.DATA_IFACE_NAME_KEY) + 178 " for " + mApnType); 179 mInterfaceName = intent.getStringExtra(Phone.DATA_IFACE_NAME_KEY); 180 } 181 return; 182 } 183 } else { 184 return; 185 } 186 187 if (DBG) Log.d(TAG, mApnType + " Received state= " + state + ", old= " + 188 mMobileDataState + ", reason= " + 189 (reason == null ? "(unspecified)" : reason) + 190 ", apnTypeList= " + apnTypeList); 191 192 if (mMobileDataState != state) { 193 mMobileDataState = state; 194 switch (state) { 195 case DISCONNECTED: 196 if(isTeardownRequested()) { 197 mEnabled = false; 198 setTeardownRequested(false); 199 } 200 201 setDetailedState(DetailedState.DISCONNECTED, reason, apnName); 202 boolean doReset = true; 203 if (mIsDefaultOrHipri == true) { 204 // both default and hipri must go down before we reset 205 int typeToCheck = (Phone.APN_TYPE_DEFAULT.equals(mApnType) ? 206 ConnectivityManager.TYPE_MOBILE_HIPRI : 207 ConnectivityManager.TYPE_MOBILE); 208 if (mConnectivityManager == null) { 209 mConnectivityManager = 210 (ConnectivityManager)context.getSystemService( 211 Context.CONNECTIVITY_SERVICE); 212 } 213 if (mConnectivityManager != null) { 214 NetworkInfo info = mConnectivityManager.getNetworkInfo( 215 typeToCheck); 216 if (info != null && info.isConnected() == true) { 217 doReset = false; 218 } 219 } 220 } 221 if (doReset && mInterfaceName != null) { 222 NetworkUtils.resetConnections(mInterfaceName); 223 } 224 // can't do this here - ConnectivityService needs it to clear stuff 225 // it's ok though - just leave it to be refreshed next time 226 // we connect. 227 //if (DBG) Log.d(TAG, "clearing mInterfaceName for "+ mApnType + 228 // " as it DISCONNECTED"); 229 //mInterfaceName = null; 230 //mDefaultGatewayAddr = 0; 231 break; 232 case CONNECTING: 233 setDetailedState(DetailedState.CONNECTING, reason, apnName); 234 break; 235 case SUSPENDED: 236 setDetailedState(DetailedState.SUSPENDED, reason, apnName); 237 break; 238 case CONNECTED: 239 mInterfaceName = intent.getStringExtra(Phone.DATA_IFACE_NAME_KEY); 240 if (mInterfaceName == null) { 241 Log.d(TAG, "CONNECTED event did not supply interface name."); 242 } 243 setDetailedState(DetailedState.CONNECTED, reason, apnName); 244 break; 245 } 246 } 247 } else if (intent.getAction(). 248 equals(TelephonyIntents.ACTION_DATA_CONNECTION_FAILED)) { 249 mEnabled = false; 250 String reason = intent.getStringExtra(Phone.FAILURE_REASON_KEY); 251 String apnName = intent.getStringExtra(Phone.DATA_APN_KEY); 252 if (DBG) Log.d(TAG, "Received " + intent.getAction() + " broadcast" + 253 reason == null ? "" : "(" + reason + ")"); 254 setDetailedState(DetailedState.FAILED, reason, apnName); 255 } 256 TelephonyManager tm = TelephonyManager.getDefault(); 257 setRoamingStatus(tm.isNetworkRoaming()); 258 setSubtype(tm.getNetworkType(), tm.getNetworkTypeName()); 259 } 260 } 261 } 262 263 private void getPhoneService(boolean forceRefresh) { 264 if ((mPhoneService == null) || forceRefresh) { 265 mPhoneService = ITelephony.Stub.asInterface(ServiceManager.getService("phone")); 266 } 267 } 268 269 /** 270 * Report whether data connectivity is possible. 271 */ 272 public boolean isAvailable() { 273 getPhoneService(false); 274 275 /* 276 * If the phone process has crashed in the past, we'll get a 277 * RemoteException and need to re-reference the service. 278 */ 279 for (int retry = 0; retry < 2; retry++) { 280 if (mPhoneService == null) break; 281 282 try { 283 return mPhoneService.isDataConnectivityPossible(); 284 } catch (RemoteException e) { 285 // First-time failed, get the phone service again 286 if (retry == 0) getPhoneService(true); 287 } 288 } 289 290 return false; 291 } 292 293 /** 294 * {@inheritDoc} 295 * The mobile data network subtype indicates what generation network technology is in effect, 296 * e.g., GPRS, EDGE, UMTS, etc. 297 */ 298 public int getNetworkSubtype() { 299 return TelephonyManager.getDefault().getNetworkType(); 300 } 301 302 /** 303 * Return the system properties name associated with the tcp buffer sizes 304 * for this network. 305 */ 306 public String getTcpBufferSizesPropName() { 307 String networkTypeStr = "unknown"; 308 TelephonyManager tm = new TelephonyManager(mContext); 309 //TODO We have to edit the parameter for getNetworkType regarding CDMA 310 switch(tm.getNetworkType()) { 311 case TelephonyManager.NETWORK_TYPE_GPRS: 312 networkTypeStr = "gprs"; 313 break; 314 case TelephonyManager.NETWORK_TYPE_EDGE: 315 networkTypeStr = "edge"; 316 break; 317 case TelephonyManager.NETWORK_TYPE_UMTS: 318 networkTypeStr = "umts"; 319 break; 320 case TelephonyManager.NETWORK_TYPE_HSDPA: 321 networkTypeStr = "hsdpa"; 322 break; 323 case TelephonyManager.NETWORK_TYPE_HSUPA: 324 networkTypeStr = "hsupa"; 325 break; 326 case TelephonyManager.NETWORK_TYPE_HSPA: 327 networkTypeStr = "hspa"; 328 break; 329 case TelephonyManager.NETWORK_TYPE_CDMA: 330 networkTypeStr = "cdma"; 331 break; 332 case TelephonyManager.NETWORK_TYPE_1xRTT: 333 networkTypeStr = "1xrtt"; 334 break; 335 case TelephonyManager.NETWORK_TYPE_EVDO_0: 336 networkTypeStr = "evdo"; 337 break; 338 case TelephonyManager.NETWORK_TYPE_EVDO_A: 339 networkTypeStr = "evdo"; 340 break; 341 case TelephonyManager.NETWORK_TYPE_EVDO_B: 342 networkTypeStr = "evdo"; 343 break; 344 } 345 return "net.tcp.buffersize." + networkTypeStr; 346 } 347 348 /** 349 * Tear down mobile data connectivity, i.e., disable the ability to create 350 * mobile data connections. 351 */ 352 @Override 353 public boolean teardown() { 354 // since we won't get a notification currently (TODO - per APN notifications) 355 // we won't get a disconnect message until all APN's on the current connection's 356 // APN list are disabled. That means privateRoutes for DNS and such will remain on - 357 // not a problem since that's all shared with whatever other APN is still on, but 358 // ugly. 359 setTeardownRequested(true); 360 return (setEnableApn(mApnType, false) != Phone.APN_REQUEST_FAILED); 361 } 362 363 /** 364 * Re-enable mobile data connectivity after a {@link #teardown()}. 365 */ 366 public boolean reconnect() { 367 setTeardownRequested(false); 368 switch (setEnableApn(mApnType, true)) { 369 case Phone.APN_ALREADY_ACTIVE: 370 // TODO - remove this when we get per-apn notifications 371 mEnabled = true; 372 // need to set self to CONNECTING so the below message is handled. 373 mMobileDataState = Phone.DataState.CONNECTING; 374 setDetailedState(DetailedState.CONNECTING, Phone.REASON_APN_CHANGED, null); 375 //send out a connected message 376 Intent intent = new Intent(TelephonyIntents. 377 ACTION_ANY_DATA_CONNECTION_STATE_CHANGED); 378 intent.putExtra(Phone.STATE_KEY, Phone.DataState.CONNECTED.toString()); 379 intent.putExtra(Phone.STATE_CHANGE_REASON_KEY, Phone.REASON_APN_CHANGED); 380 intent.putExtra(Phone.DATA_APN_TYPES_KEY, mApnTypeToWatchFor); 381 intent.putExtra(Phone.DATA_APN_KEY, mApnName); 382 intent.putExtra(Phone.DATA_IFACE_NAME_KEY, mInterfaceName); 383 intent.putExtra(Phone.NETWORK_UNAVAILABLE_KEY, false); 384 if (mStateReceiver != null) mStateReceiver.onReceive(mContext, intent); 385 break; 386 case Phone.APN_REQUEST_STARTED: 387 mEnabled = true; 388 // no need to do anything - we're already due some status update intents 389 break; 390 case Phone.APN_REQUEST_FAILED: 391 if (mPhoneService == null && mApnType == Phone.APN_TYPE_DEFAULT) { 392 // on startup we may try to talk to the phone before it's ready 393 // since the phone will come up enabled, go with that. 394 // TODO - this also comes up on telephony crash: if we think mobile data is 395 // off and the telephony stuff crashes and has to restart it will come up 396 // enabled (making a data connection). We will then be out of sync. 397 // A possible solution is a broadcast when telephony restarts. 398 mEnabled = true; 399 return false; 400 } 401 // else fall through 402 case Phone.APN_TYPE_NOT_AVAILABLE: 403 // Default is always available, but may be off due to 404 // AirplaneMode or E-Call or whatever.. 405 if (mApnType != Phone.APN_TYPE_DEFAULT) { 406 mEnabled = false; 407 } 408 break; 409 default: 410 Log.e(TAG, "Error in reconnect - unexpected response."); 411 mEnabled = false; 412 break; 413 } 414 return mEnabled; 415 } 416 417 /** 418 * Turn on or off the mobile radio. No connectivity will be possible while the 419 * radio is off. The operation is a no-op if the radio is already in the desired state. 420 * @param turnOn {@code true} if the radio should be turned on, {@code false} if 421 */ 422 public boolean setRadio(boolean turnOn) { 423 getPhoneService(false); 424 /* 425 * If the phone process has crashed in the past, we'll get a 426 * RemoteException and need to re-reference the service. 427 */ 428 for (int retry = 0; retry < 2; retry++) { 429 if (mPhoneService == null) { 430 Log.w(TAG, 431 "Ignoring mobile radio request because could not acquire PhoneService"); 432 break; 433 } 434 435 try { 436 return mPhoneService.setRadio(turnOn); 437 } catch (RemoteException e) { 438 if (retry == 0) getPhoneService(true); 439 } 440 } 441 442 Log.w(TAG, "Could not set radio power to " + (turnOn ? "on" : "off")); 443 return false; 444 } 445 446 /** 447 * Tells the phone sub-system that the caller wants to 448 * begin using the named feature. The only supported features at 449 * this time are {@code Phone.FEATURE_ENABLE_MMS}, which allows an application 450 * to specify that it wants to send and/or receive MMS data, and 451 * {@code Phone.FEATURE_ENABLE_SUPL}, which is used for Assisted GPS. 452 * @param feature the name of the feature to be used 453 * @param callingPid the process ID of the process that is issuing this request 454 * @param callingUid the user ID of the process that is issuing this request 455 * @return an integer value representing the outcome of the request. 456 * The interpretation of this value is feature-specific. 457 * specific, except that the value {@code -1} 458 * always indicates failure. For {@code Phone.FEATURE_ENABLE_MMS}, 459 * the other possible return values are 460 * <ul> 461 * <li>{@code Phone.APN_ALREADY_ACTIVE}</li> 462 * <li>{@code Phone.APN_REQUEST_STARTED}</li> 463 * <li>{@code Phone.APN_TYPE_NOT_AVAILABLE}</li> 464 * <li>{@code Phone.APN_REQUEST_FAILED}</li> 465 * </ul> 466 */ 467 public int startUsingNetworkFeature(String feature, int callingPid, int callingUid) { 468 return -1; 469 } 470 471 /** 472 * Tells the phone sub-system that the caller is finished 473 * using the named feature. The only supported feature at 474 * this time is {@code Phone.FEATURE_ENABLE_MMS}, which allows an application 475 * to specify that it wants to send and/or receive MMS data. 476 * @param feature the name of the feature that is no longer needed 477 * @param callingPid the process ID of the process that is issuing this request 478 * @param callingUid the user ID of the process that is issuing this request 479 * @return an integer value representing the outcome of the request. 480 * The interpretation of this value is feature-specific, except that 481 * the value {@code -1} always indicates failure. 482 */ 483 public int stopUsingNetworkFeature(String feature, int callingPid, int callingUid) { 484 return -1; 485 } 486 487 /** 488 * Ensure that a network route exists to deliver traffic to the specified 489 * host via the mobile data network. 490 * @param hostAddress the IP address of the host to which the route is desired, 491 * in network byte order. 492 * @return {@code true} on success, {@code false} on failure 493 */ 494 @Override 495 public boolean requestRouteToHost(int hostAddress) { 496 if (DBG) { 497 Log.d(TAG, "Requested host route to " + Integer.toHexString(hostAddress) + 498 " for " + mApnType + "(" + mInterfaceName + ")"); 499 } 500 if (mInterfaceName != null && hostAddress != -1) { 501 return NetworkUtils.addHostRoute(mInterfaceName, hostAddress) == 0; 502 } else { 503 return false; 504 } 505 } 506 507 @Override 508 public String toString() { 509 StringBuffer sb = new StringBuffer("Mobile data state: "); 510 511 sb.append(mMobileDataState); 512 return sb.toString(); 513 } 514 515 /** 516 * Internal method supporting the ENABLE_MMS feature. 517 * @param apnType the type of APN to be enabled or disabled (e.g., mms) 518 * @param enable {@code true} to enable the specified APN type, 519 * {@code false} to disable it. 520 * @return an integer value representing the outcome of the request. 521 */ 522 private int setEnableApn(String apnType, boolean enable) { 523 getPhoneService(false); 524 /* 525 * If the phone process has crashed in the past, we'll get a 526 * RemoteException and need to re-reference the service. 527 */ 528 for (int retry = 0; retry < 2; retry++) { 529 if (mPhoneService == null) { 530 Log.w(TAG, 531 "Ignoring feature request because could not acquire PhoneService"); 532 break; 533 } 534 535 try { 536 if (enable) { 537 return mPhoneService.enableApnType(apnType); 538 } else { 539 return mPhoneService.disableApnType(apnType); 540 } 541 } catch (RemoteException e) { 542 if (retry == 0) getPhoneService(true); 543 } 544 } 545 546 Log.w(TAG, "Could not " + (enable ? "enable" : "disable") 547 + " APN type \"" + apnType + "\""); 548 return Phone.APN_REQUEST_FAILED; 549 } 550 551 public static String networkTypeToApnType(int netType) { 552 switch(netType) { 553 case ConnectivityManager.TYPE_MOBILE: 554 return Phone.APN_TYPE_DEFAULT; // TODO - use just one of these 555 case ConnectivityManager.TYPE_MOBILE_MMS: 556 return Phone.APN_TYPE_MMS; 557 case ConnectivityManager.TYPE_MOBILE_SUPL: 558 return Phone.APN_TYPE_SUPL; 559 case ConnectivityManager.TYPE_MOBILE_DUN: 560 return Phone.APN_TYPE_DUN; 561 case ConnectivityManager.TYPE_MOBILE_HIPRI: 562 return Phone.APN_TYPE_HIPRI; 563 default: 564 Log.e(TAG, "Error mapping networkType " + netType + " to apnType."); 565 return null; 566 } 567 } 568} 569