MobileDataStateTracker.java revision ebe66345e7099ca6fc95e8aa4d31a5b5cbbd6224
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 boolean mEnabled; 52 private BroadcastReceiver mStateReceiver; 53 54 /** 55 * Create a new MobileDataStateTracker 56 * @param context the application context of the caller 57 * @param target a message handler for getting callbacks about state changes 58 * @param netType the ConnectivityManager network type 59 * @param apnType the Phone apnType 60 * @param tag the name of this network 61 */ 62 public MobileDataStateTracker(Context context, Handler target, 63 int netType, String apnType, String tag) { 64 super(context, target, netType, 65 TelephonyManager.getDefault().getNetworkType(), tag, 66 TelephonyManager.getDefault().getNetworkTypeName()); 67 mApnType = apnType; 68 mPhoneService = null; 69 if(netType == ConnectivityManager.TYPE_MOBILE) { 70 mEnabled = true; 71 } else { 72 mEnabled = false; 73 } 74 75 mDnsPropNames = new String[] { 76 "net.rmnet0.dns1", 77 "net.rmnet0.dns2", 78 "net.eth0.dns1", 79 "net.eth0.dns2", 80 "net.eth0.dns3", 81 "net.eth0.dns4", 82 "net.gprs.dns1", 83 "net.gprs.dns2", 84 "net.ppp0.dns1", 85 "net.ppp0.dns2"}; 86 87 } 88 89 /** 90 * Begin monitoring mobile data connectivity. 91 */ 92 public void startMonitoring() { 93 IntentFilter filter = 94 new IntentFilter(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED); 95 filter.addAction(TelephonyIntents.ACTION_DATA_CONNECTION_FAILED); 96 filter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED); 97 98 mStateReceiver = new MobileDataStateReceiver(); 99 Intent intent = mContext.registerReceiver(mStateReceiver, filter); 100 if (intent != null) 101 mMobileDataState = getMobileDataState(intent); 102 else 103 mMobileDataState = Phone.DataState.DISCONNECTED; 104 } 105 106 private Phone.DataState getMobileDataState(Intent intent) { 107 String str = intent.getStringExtra(Phone.STATE_KEY); 108 if (str != null) { 109 String apnTypeList = 110 intent.getStringExtra(Phone.DATA_APN_TYPES_KEY); 111 if (isApnTypeIncluded(apnTypeList)) { 112 return Enum.valueOf(Phone.DataState.class, str); 113 } 114 } 115 return Phone.DataState.DISCONNECTED; 116 } 117 118 private boolean isApnTypeIncluded(String typeList) { 119 /* comma seperated list - split and check */ 120 if (typeList == null) 121 return false; 122 123 String[] list = typeList.split(","); 124 for(int i=0; i< list.length; i++) { 125 if (TextUtils.equals(list[i], mApnType) || 126 TextUtils.equals(list[i], Phone.APN_TYPE_ALL)) { 127 return true; 128 } 129 } 130 return false; 131 } 132 133 private class MobileDataStateReceiver extends BroadcastReceiver { 134 public void onReceive(Context context, Intent intent) { 135 synchronized(this) { 136 if (intent.getAction().equals(TelephonyIntents. 137 ACTION_ANY_DATA_CONNECTION_STATE_CHANGED)) { 138 Phone.DataState state = getMobileDataState(intent); 139 String reason = intent.getStringExtra(Phone.STATE_CHANGE_REASON_KEY); 140 String apnName = intent.getStringExtra(Phone.DATA_APN_KEY); 141 String apnTypeList = intent.getStringExtra(Phone.DATA_APN_TYPES_KEY); 142 143 boolean unavailable = intent.getBooleanExtra(Phone.NETWORK_UNAVAILABLE_KEY, 144 false); 145 if (DBG) Log.d(TAG, mApnType + " Received " + intent.getAction() + 146 " broadcast - state = " + state + ", oldstate = " + mMobileDataState + 147 ", unavailable = " + unavailable + ", reason = " + 148 (reason == null ? "(unspecified)" : reason)); 149 150 if (isApnTypeIncluded(apnTypeList)) { 151 if (mEnabled == false) { 152 // if we're not enabled but the APN Type is supported by this connection 153 // we should record the interface name if one's provided. If the user 154 // turns on this network we will need the interfacename but won't get 155 // a fresh connected message - TODO fix this.. 156 if (state == Phone.DataState.CONNECTED) { 157 if (DBG) Log.d(TAG, "replacing old mInterfaceName (" + 158 mInterfaceName + ") with " + 159 intent.getStringExtra(Phone.DATA_IFACE_NAME_KEY) + 160 " for " + mApnType); 161 mInterfaceName = intent.getStringExtra(Phone.DATA_IFACE_NAME_KEY); 162 } 163 if (DBG) Log.d(TAG, " dropped - mEnabled = false"); 164 return; 165 } 166 } else { 167 if (DBG) Log.d(TAG, " dropped - wrong Apn"); 168 return; 169 } 170 171 mNetworkInfo.setIsAvailable(!unavailable); 172 if (mMobileDataState != state) { 173 mMobileDataState = state; 174 switch (state) { 175 case DISCONNECTED: 176 if(isTeardownRequested()) { 177 mEnabled = false; 178 setTeardownRequested(false); 179 } 180 181 setDetailedState(DetailedState.DISCONNECTED, reason, apnName); 182 if (mInterfaceName != null) { 183 NetworkUtils.resetConnections(mInterfaceName); 184 } 185 if (DBG) Log.d(TAG, "clearing mInterfaceName for "+ mApnType + 186 " as it DISCONNECTED"); 187 mInterfaceName = null; 188 mDefaultGatewayAddr = 0; 189 break; 190 case CONNECTING: 191 setDetailedState(DetailedState.CONNECTING, reason, apnName); 192 break; 193 case SUSPENDED: 194 setDetailedState(DetailedState.SUSPENDED, reason, apnName); 195 break; 196 case CONNECTED: 197 mInterfaceName = intent.getStringExtra(Phone.DATA_IFACE_NAME_KEY); 198 if (mInterfaceName == null) { 199 Log.d(TAG, "CONNECTED event did not supply interface name."); 200 } 201 setDetailedState(DetailedState.CONNECTED, reason, apnName); 202 break; 203 } 204 } 205 } else if (intent.getAction(). 206 equals(TelephonyIntents.ACTION_DATA_CONNECTION_FAILED)) { 207 mEnabled = false; 208 String reason = intent.getStringExtra(Phone.FAILURE_REASON_KEY); 209 String apnName = intent.getStringExtra(Phone.DATA_APN_KEY); 210 if (DBG) Log.d(TAG, "Received " + intent.getAction() + " broadcast" + 211 reason == null ? "" : "(" + reason + ")"); 212 setDetailedState(DetailedState.FAILED, reason, apnName); 213 } 214 TelephonyManager tm = TelephonyManager.getDefault(); 215 setRoamingStatus(tm.isNetworkRoaming()); 216 setSubtype(tm.getNetworkType(), tm.getNetworkTypeName()); 217 } 218 } 219 } 220 221 private void getPhoneService(boolean forceRefresh) { 222 if ((mPhoneService == null) || forceRefresh) { 223 mPhoneService = ITelephony.Stub.asInterface(ServiceManager.getService("phone")); 224 } 225 } 226 227 /** 228 * Report whether data connectivity is possible. 229 */ 230 public boolean isAvailable() { 231 getPhoneService(false); 232 233 /* 234 * If the phone process has crashed in the past, we'll get a 235 * RemoteException and need to re-reference the service. 236 */ 237 for (int retry = 0; retry < 2; retry++) { 238 if (mPhoneService == null) break; 239 240 try { 241 return mPhoneService.isDataConnectivityPossible(); 242 } catch (RemoteException e) { 243 // First-time failed, get the phone service again 244 if (retry == 0) getPhoneService(true); 245 } 246 } 247 248 return false; 249 } 250 251 /** 252 * {@inheritDoc} 253 * The mobile data network subtype indicates what generation network technology is in effect, 254 * e.g., GPRS, EDGE, UMTS, etc. 255 */ 256 public int getNetworkSubtype() { 257 return TelephonyManager.getDefault().getNetworkType(); 258 } 259 260 /** 261 * Return the system properties name associated with the tcp buffer sizes 262 * for this network. 263 */ 264 public String getTcpBufferSizesPropName() { 265 String networkTypeStr = "unknown"; 266 TelephonyManager tm = new TelephonyManager(mContext); 267 //TODO We have to edit the parameter for getNetworkType regarding CDMA 268 switch(tm.getNetworkType()) { 269 case TelephonyManager.NETWORK_TYPE_GPRS: 270 networkTypeStr = "gprs"; 271 break; 272 case TelephonyManager.NETWORK_TYPE_EDGE: 273 networkTypeStr = "edge"; 274 break; 275 case TelephonyManager.NETWORK_TYPE_UMTS: 276 networkTypeStr = "umts"; 277 break; 278 case TelephonyManager.NETWORK_TYPE_HSDPA: 279 networkTypeStr = "hsdpa"; 280 break; 281 case TelephonyManager.NETWORK_TYPE_HSUPA: 282 networkTypeStr = "hsupa"; 283 break; 284 case TelephonyManager.NETWORK_TYPE_HSPA: 285 networkTypeStr = "hspa"; 286 break; 287 case TelephonyManager.NETWORK_TYPE_CDMA: 288 networkTypeStr = "cdma"; 289 break; 290 case TelephonyManager.NETWORK_TYPE_1xRTT: 291 networkTypeStr = "1xrtt"; 292 break; 293 case TelephonyManager.NETWORK_TYPE_EVDO_0: 294 networkTypeStr = "evdo"; 295 break; 296 case TelephonyManager.NETWORK_TYPE_EVDO_A: 297 networkTypeStr = "evdo"; 298 break; 299 } 300 return "net.tcp.buffersize." + networkTypeStr; 301 } 302 303 /** 304 * Tear down mobile data connectivity, i.e., disable the ability to create 305 * mobile data connections. 306 */ 307 @Override 308 public boolean teardown() { 309 setTeardownRequested(true); 310 return (setEnableApn(mApnType, false) != Phone.APN_REQUEST_FAILED); 311 } 312 313 /** 314 * Re-enable mobile data connectivity after a {@link #teardown()}. 315 */ 316 public boolean reconnect() { 317 setTeardownRequested(false); 318 switch (setEnableApn(mApnType, true)) { 319 case Phone.APN_ALREADY_ACTIVE: 320 mEnabled = true; 321 // need to set self to CONNECTING so the below message is handled. 322 mMobileDataState = Phone.DataState.CONNECTING; 323 //send out a connected message 324 Intent intent = new Intent(TelephonyIntents. 325 ACTION_ANY_DATA_CONNECTION_STATE_CHANGED); 326 intent.putExtra(Phone.STATE_KEY, Phone.DataState.CONNECTED.toString()); 327 intent.putExtra(Phone.STATE_CHANGE_REASON_KEY, Phone.REASON_APN_CHANGED); 328 intent.putExtra(Phone.DATA_APN_TYPES_KEY, mApnType); 329 intent.putExtra(Phone.DATA_IFACE_NAME_KEY, mInterfaceName); 330 intent.putExtra(Phone.NETWORK_UNAVAILABLE_KEY, false); 331 if (mStateReceiver != null) mStateReceiver.onReceive(mContext, intent); 332 break; 333 case Phone.APN_REQUEST_STARTED: 334 mEnabled = true; 335 // no need to do anything - we're already due some status update intents 336 break; 337 case Phone.APN_REQUEST_FAILED: 338 if (mPhoneService == null && mApnType == Phone.APN_TYPE_DEFAULT) { 339 // on startup we may try to talk to the phone before it's ready 340 // just leave mEnabled as it is for the default apn. 341 return false; 342 } 343 // else fall through 344 case Phone.APN_TYPE_NOT_AVAILABLE: 345 mEnabled = false; 346 break; 347 default: 348 Log.e(TAG, "Error in reconnect - unexpected response."); 349 mEnabled = false; 350 break; 351 } 352 return mEnabled; 353 } 354 355 /** 356 * Turn on or off the mobile radio. No connectivity will be possible while the 357 * radio is off. The operation is a no-op if the radio is already in the desired state. 358 * @param turnOn {@code true} if the radio should be turned on, {@code false} if 359 */ 360 public boolean setRadio(boolean turnOn) { 361 getPhoneService(false); 362 /* 363 * If the phone process has crashed in the past, we'll get a 364 * RemoteException and need to re-reference the service. 365 */ 366 for (int retry = 0; retry < 2; retry++) { 367 if (mPhoneService == null) { 368 Log.w(TAG, 369 "Ignoring mobile radio request because could not acquire PhoneService"); 370 break; 371 } 372 373 try { 374 return mPhoneService.setRadio(turnOn); 375 } catch (RemoteException e) { 376 if (retry == 0) getPhoneService(true); 377 } 378 } 379 380 Log.w(TAG, "Could not set radio power to " + (turnOn ? "on" : "off")); 381 return false; 382 } 383 384 /** 385 * Tells the phone sub-system that the caller wants to 386 * begin using the named feature. The only supported features at 387 * this time are {@code Phone.FEATURE_ENABLE_MMS}, which allows an application 388 * to specify that it wants to send and/or receive MMS data, and 389 * {@code Phone.FEATURE_ENABLE_SUPL}, which is used for Assisted GPS. 390 * @param feature the name of the feature to be used 391 * @param callingPid the process ID of the process that is issuing this request 392 * @param callingUid the user ID of the process that is issuing this request 393 * @return an integer value representing the outcome of the request. 394 * The interpretation of this value is feature-specific. 395 * specific, except that the value {@code -1} 396 * always indicates failure. For {@code Phone.FEATURE_ENABLE_MMS}, 397 * the other possible return values are 398 * <ul> 399 * <li>{@code Phone.APN_ALREADY_ACTIVE}</li> 400 * <li>{@code Phone.APN_REQUEST_STARTED}</li> 401 * <li>{@code Phone.APN_TYPE_NOT_AVAILABLE}</li> 402 * <li>{@code Phone.APN_REQUEST_FAILED}</li> 403 * </ul> 404 */ 405 public int startUsingNetworkFeature(String feature, int callingPid, int callingUid) { 406 return -1; 407 } 408 409 /** 410 * Tells the phone sub-system that the caller is finished 411 * using the named feature. The only supported feature at 412 * this time is {@code Phone.FEATURE_ENABLE_MMS}, which allows an application 413 * to specify that it wants to send and/or receive MMS data. 414 * @param feature the name of the feature that is no longer needed 415 * @param callingPid the process ID of the process that is issuing this request 416 * @param callingUid the user ID of the process that is issuing this request 417 * @return an integer value representing the outcome of the request. 418 * The interpretation of this value is feature-specific, except that 419 * the value {@code -1} always indicates failure. 420 */ 421 public int stopUsingNetworkFeature(String feature, int callingPid, int callingUid) { 422 return -1; 423 } 424 425 /** 426 * Ensure that a network route exists to deliver traffic to the specified 427 * host via the mobile data network. 428 * @param hostAddress the IP address of the host to which the route is desired, 429 * in network byte order. 430 * @return {@code true} on success, {@code false} on failure 431 */ 432 @Override 433 public boolean requestRouteToHost(int hostAddress) { 434 if (DBG) { 435 Log.d(TAG, "Requested host route to " + Integer.toHexString(hostAddress) + 436 " for " + mApnType + "(" + mInterfaceName + ")"); 437 } 438 if (mInterfaceName != null && hostAddress != -1) { 439 return NetworkUtils.addHostRoute(mInterfaceName, hostAddress) == 0; 440 } else { 441 return false; 442 } 443 } 444 445 @Override 446 public String toString() { 447 StringBuffer sb = new StringBuffer("Mobile data state: "); 448 449 sb.append(mMobileDataState); 450 return sb.toString(); 451 } 452 453 /** 454 * Internal method supporting the ENABLE_MMS feature. 455 * @param apnType the type of APN to be enabled or disabled (e.g., mms) 456 * @param enable {@code true} to enable the specified APN type, 457 * {@code false} to disable it. 458 * @return an integer value representing the outcome of the request. 459 */ 460 private int setEnableApn(String apnType, boolean enable) { 461 getPhoneService(false); 462 /* 463 * If the phone process has crashed in the past, we'll get a 464 * RemoteException and need to re-reference the service. 465 */ 466 for (int retry = 0; retry < 2; retry++) { 467 if (mPhoneService == null) { 468 Log.w(TAG, 469 "Ignoring feature request because could not acquire PhoneService"); 470 break; 471 } 472 473 try { 474 if (enable) { 475 return mPhoneService.enableApnType(apnType); 476 } else { 477 return mPhoneService.disableApnType(apnType); 478 } 479 } catch (RemoteException e) { 480 if (retry == 0) getPhoneService(true); 481 } 482 } 483 484 Log.w(TAG, "Could not " + (enable ? "enable" : "disable") 485 + " APN type \"" + apnType + "\""); 486 return Phone.APN_REQUEST_FAILED; 487 } 488} 489