2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 import android.content.BroadcastReceiver;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.IntentFilter;
23 import android.net.NetworkInfo.DetailedState;
24 import android.os.Bundle;
25 import android.os.Handler;
26 import android.os.Looper;
27 import android.os.Message;
28 import android.os.Messenger;
29 import android.os.RemoteException;
30 import android.os.ServiceManager;
31 import android.telephony.TelephonyManager;
32 import android.text.TextUtils;
33 import android.util.Slog;
35 import com.android.internal.telephony.DctConstants;
36 import com.android.internal.telephony.ITelephony;
37 import com.android.internal.telephony.PhoneConstants;
38 import com.android.internal.telephony.TelephonyIntents;
39 import com.android.internal.util.AsyncChannel;
41 import java.io.CharArrayWriter;
42 import java.io.PrintWriter;
43 import java.util.concurrent.atomic.AtomicBoolean;
46 * Track the state of mobile data connectivity. This is done by
47 * receiving broadcast intents from the Phone process whenever
48 * the state of data connectivity changes.
52 public class MobileDataStateTracker implements NetworkStateTracker {
54 private static final String TAG = "MobileDataStateTracker";
55 private static final boolean DBG = false;
56 private static final boolean VDBG = false;
58 private PhoneConstants.DataState mMobileDataState;
59 private ITelephony mPhoneService;
61 private String mApnType;
62 private NetworkInfo mNetworkInfo;
63 private boolean mTeardownRequested = false;
64 private Handler mTarget;
65 private Context mContext;
66 private LinkProperties mLinkProperties;
67 private LinkCapabilities mLinkCapabilities;
68 private boolean mPrivateDnsRouteSet = false;
69 private boolean mDefaultRouteSet = false;
71 // NOTE: these are only kept for debugging output; actual values are
72 // maintained in DataConnectionTracker.
73 protected boolean mUserDataEnabled = true;
74 protected boolean mPolicyDataEnabled = true;
76 private Handler mHandler;
77 private AsyncChannel mDataConnectionTrackerAc;
79 private AtomicBoolean mIsCaptivePortal = new AtomicBoolean(false);
82 * Create a new MobileDataStateTracker
83 * @param netType the ConnectivityManager network type
84 * @param tag the name of this network
86 public MobileDataStateTracker(int netType, String tag) {
87 mNetworkInfo = new NetworkInfo(netType,
88 TelephonyManager.getDefault().getNetworkType(), tag,
89 TelephonyManager.getDefault().getNetworkTypeName());
90 mApnType = networkTypeToApnType(netType);
94 * Begin monitoring data connectivity.
96 * @param context is the current Android context
97 * @param target is the Hander to which to return the events.
99 public void startMonitoring(Context context, Handler target) {
103 mHandler = new MdstHandler(target.getLooper(), this);
105 IntentFilter filter = new IntentFilter();
106 filter.addAction(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED);
107 filter.addAction(TelephonyIntents.ACTION_DATA_CONNECTION_FAILED);
109 mContext.registerReceiver(new MobileDataStateReceiver(), filter);
110 mMobileDataState = PhoneConstants.DataState.DISCONNECTED;
113 static class MdstHandler extends Handler {
114 private MobileDataStateTracker mMdst;
116 MdstHandler(Looper looper, MobileDataStateTracker mdst) {
122 public void handleMessage(Message msg) {
124 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED:
125 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
127 mMdst.log("MdstHandler connected");
129 mMdst.mDataConnectionTrackerAc = (AsyncChannel) msg.obj;
132 mMdst.log("MdstHandler %s NOT connected error=" + msg.arg1);
136 case AsyncChannel.CMD_CHANNEL_DISCONNECTED:
137 if (VDBG) mMdst.log("Disconnected from DataStateTracker");
138 mMdst.mDataConnectionTrackerAc = null;
141 if (VDBG) mMdst.log("Ignorning unknown message=" + msg);
148 public boolean isPrivateDnsRouteSet() {
149 return mPrivateDnsRouteSet;
152 public void privateDnsRouteSet(boolean enabled) {
153 mPrivateDnsRouteSet = enabled;
156 public NetworkInfo getNetworkInfo() {
160 public boolean isDefaultRouteSet() {
161 return mDefaultRouteSet;
164 public void defaultRouteSet(boolean enabled) {
165 mDefaultRouteSet = enabled;
169 * This is not implemented.
171 public void releaseWakeLock() {
174 private class MobileDataStateReceiver extends BroadcastReceiver {
176 public void onReceive(Context context, Intent intent) {
177 if (intent.getAction().equals(TelephonyIntents.
178 ACTION_ANY_DATA_CONNECTION_STATE_CHANGED)) {
179 String apnType = intent.getStringExtra(PhoneConstants.DATA_APN_TYPE_KEY);
181 log(String.format("Broadcast received: ACTION_ANY_DATA_CONNECTION_STATE_CHANGED"
182 + "mApnType=%s %s received apnType=%s", mApnType,
183 TextUtils.equals(apnType, mApnType) ? "==" : "!=", apnType));
185 if (!TextUtils.equals(apnType, mApnType)) {
189 int oldSubtype = mNetworkInfo.getSubtype();
190 int newSubType = TelephonyManager.getDefault().getNetworkType();
191 String subTypeName = TelephonyManager.getDefault().getNetworkTypeName();
192 mNetworkInfo.setSubtype(newSubType, subTypeName);
193 if (newSubType != oldSubtype && mNetworkInfo.isConnected()) {
194 Message msg = mTarget.obtainMessage(EVENT_NETWORK_SUBTYPE_CHANGED,
195 oldSubtype, 0, mNetworkInfo);
199 PhoneConstants.DataState state = Enum.valueOf(PhoneConstants.DataState.class,
200 intent.getStringExtra(PhoneConstants.STATE_KEY));
201 String reason = intent.getStringExtra(PhoneConstants.STATE_CHANGE_REASON_KEY);
202 String apnName = intent.getStringExtra(PhoneConstants.DATA_APN_KEY);
203 mNetworkInfo.setRoaming(intent.getBooleanExtra(
204 PhoneConstants.DATA_NETWORK_ROAMING_KEY, false));
206 log(mApnType + " setting isAvailable to " +
207 intent.getBooleanExtra(PhoneConstants.NETWORK_UNAVAILABLE_KEY,false));
209 mNetworkInfo.setIsAvailable(!intent.getBooleanExtra(
210 PhoneConstants.NETWORK_UNAVAILABLE_KEY, false));
213 log("Received state=" + state + ", old=" + mMobileDataState +
214 ", reason=" + (reason == null ? "(unspecified)" : reason));
216 if (mMobileDataState != state) {
217 mMobileDataState = state;
220 if(isTeardownRequested()) {
221 setTeardownRequested(false);
224 setDetailedState(DetailedState.DISCONNECTED, reason, apnName);
225 // can't do this here - ConnectivityService needs it to clear stuff
226 // it's ok though - just leave it to be refreshed next time
228 //if (DBG) log("clearing mInterfaceName for "+ mApnType +
229 // " as it DISCONNECTED");
230 //mInterfaceName = null;
233 setDetailedState(DetailedState.CONNECTING, reason, apnName);
236 setDetailedState(DetailedState.SUSPENDED, reason, apnName);
239 mLinkProperties = intent.getParcelableExtra(
240 PhoneConstants.DATA_LINK_PROPERTIES_KEY);
241 if (mLinkProperties == null) {
242 loge("CONNECTED event did not supply link properties.");
243 mLinkProperties = new LinkProperties();
245 mLinkCapabilities = intent.getParcelableExtra(
246 PhoneConstants.DATA_LINK_CAPABILITIES_KEY);
247 if (mLinkCapabilities == null) {
248 loge("CONNECTED event did not supply link capabilities.");
249 mLinkCapabilities = new LinkCapabilities();
251 setDetailedState(DetailedState.CONNECTED, reason, apnName);
255 // There was no state change. Check if LinkProperties has been updated.
256 if (TextUtils.equals(reason, PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
257 mLinkProperties = intent.getParcelableExtra(
258 PhoneConstants.DATA_LINK_PROPERTIES_KEY);
259 if (mLinkProperties == null) {
260 loge("No link property in LINK_PROPERTIES change event.");
261 mLinkProperties = new LinkProperties();
263 // Just update reason field in this NetworkInfo
264 mNetworkInfo.setDetailedState(mNetworkInfo.getDetailedState(), reason,
265 mNetworkInfo.getExtraInfo());
266 Message msg = mTarget.obtainMessage(EVENT_CONFIGURATION_CHANGED,
271 } else if (intent.getAction().
272 equals(TelephonyIntents.ACTION_DATA_CONNECTION_FAILED)) {
273 String apnType = intent.getStringExtra(PhoneConstants.DATA_APN_TYPE_KEY);
274 if (!TextUtils.equals(apnType, mApnType)) {
277 "Broadcast received: ACTION_ANY_DATA_CONNECTION_FAILED ignore, " +
278 "mApnType=%s != received apnType=%s", mApnType, apnType));
282 String reason = intent.getStringExtra(PhoneConstants.FAILURE_REASON_KEY);
283 String apnName = intent.getStringExtra(PhoneConstants.DATA_APN_KEY);
285 log("Received " + intent.getAction() +
286 " broadcast" + reason == null ? "" : "(" + reason + ")");
288 setDetailedState(DetailedState.FAILED, reason, apnName);
290 if (DBG) log("Broadcast received: ignore " + intent.getAction());
295 private void getPhoneService(boolean forceRefresh) {
296 if ((mPhoneService == null) || forceRefresh) {
297 mPhoneService = ITelephony.Stub.asInterface(ServiceManager.getService("phone"));
302 * Report whether data connectivity is possible.
304 public boolean isAvailable() {
305 return mNetworkInfo.isAvailable();
309 * Return the system properties name associated with the tcp buffer sizes
312 public String getTcpBufferSizesPropName() {
313 String networkTypeStr = "unknown";
314 TelephonyManager tm = new TelephonyManager(mContext);
315 //TODO We have to edit the parameter for getNetworkType regarding CDMA
316 switch(tm.getNetworkType()) {
317 case TelephonyManager.NETWORK_TYPE_GPRS:
318 networkTypeStr = "gprs";
320 case TelephonyManager.NETWORK_TYPE_EDGE:
321 networkTypeStr = "edge";
323 case TelephonyManager.NETWORK_TYPE_UMTS:
324 networkTypeStr = "umts";
326 case TelephonyManager.NETWORK_TYPE_HSDPA:
327 networkTypeStr = "hsdpa";
329 case TelephonyManager.NETWORK_TYPE_HSUPA:
330 networkTypeStr = "hsupa";
332 case TelephonyManager.NETWORK_TYPE_HSPA:
333 networkTypeStr = "hspa";
335 case TelephonyManager.NETWORK_TYPE_HSPAP:
336 networkTypeStr = "hspap";
338 case TelephonyManager.NETWORK_TYPE_CDMA:
339 networkTypeStr = "cdma";
341 case TelephonyManager.NETWORK_TYPE_1xRTT:
342 networkTypeStr = "1xrtt";
344 case TelephonyManager.NETWORK_TYPE_EVDO_0:
345 networkTypeStr = "evdo";
347 case TelephonyManager.NETWORK_TYPE_EVDO_A:
348 networkTypeStr = "evdo";
350 case TelephonyManager.NETWORK_TYPE_EVDO_B:
351 networkTypeStr = "evdo";
353 case TelephonyManager.NETWORK_TYPE_IDEN:
354 networkTypeStr = "iden";
356 case TelephonyManager.NETWORK_TYPE_LTE:
357 networkTypeStr = "lte";
359 case TelephonyManager.NETWORK_TYPE_EHRPD:
360 networkTypeStr = "ehrpd";
363 loge("unknown network type: " + tm.getNetworkType());
365 return "net.tcp.buffersize." + networkTypeStr;
369 * Tear down mobile data connectivity, i.e., disable the ability to create
370 * mobile data connections.
371 * TODO - make async and return nothing?
373 public boolean teardown() {
374 setTeardownRequested(true);
375 return (setEnableApn(mApnType, false) != PhoneConstants.APN_REQUEST_FAILED);
379 public void captivePortalCheckComplete() {
384 public void captivePortalCheckCompleted(boolean isCaptivePortal) {
385 if (mIsCaptivePortal.getAndSet(isCaptivePortal) != isCaptivePortal) {
386 // Captive portal change enable/disable failing fast
387 setEnableFailFastMobileData(
388 isCaptivePortal ? DctConstants.ENABLED : DctConstants.DISABLED);
393 * Record the detailed state of a network, and if it is a
394 * change from the previous state, send a notification to
396 * @param state the new {@code DetailedState}
397 * @param reason a {@code String} indicating a reason for the state change,
398 * if one was supplied. May be {@code null}.
399 * @param extraInfo optional {@code String} providing extra information about the state change
401 private void setDetailedState(NetworkInfo.DetailedState state, String reason,
403 if (DBG) log("setDetailed state, old ="
404 + mNetworkInfo.getDetailedState() + " and new state=" + state);
405 if (state != mNetworkInfo.getDetailedState()) {
406 boolean wasConnecting = (mNetworkInfo.getState() == NetworkInfo.State.CONNECTING);
407 String lastReason = mNetworkInfo.getReason();
409 * If a reason was supplied when the CONNECTING state was entered, and no
410 * reason was supplied for entering the CONNECTED state, then retain the
411 * reason that was supplied when going to CONNECTING.
413 if (wasConnecting && state == NetworkInfo.DetailedState.CONNECTED && reason == null
414 && lastReason != null)
416 mNetworkInfo.setDetailedState(state, reason, extraInfo);
417 Message msg = mTarget.obtainMessage(EVENT_STATE_CHANGED, new NetworkInfo(mNetworkInfo));
422 public void setTeardownRequested(boolean isRequested) {
423 mTeardownRequested = isRequested;
426 public boolean isTeardownRequested() {
427 return mTeardownRequested;
431 * Re-enable mobile data connectivity after a {@link #teardown()}.
432 * TODO - make async and always get a notification?
434 public boolean reconnect() {
435 boolean retValue = false; //connected or expect to be?
436 setTeardownRequested(false);
437 switch (setEnableApn(mApnType, true)) {
438 case PhoneConstants.APN_ALREADY_ACTIVE:
439 // need to set self to CONNECTING so the below message is handled.
442 case PhoneConstants.APN_REQUEST_STARTED:
443 // set IDLE here , avoid the following second FAILED not sent out
444 mNetworkInfo.setDetailedState(DetailedState.IDLE, null, null);
447 case PhoneConstants.APN_REQUEST_FAILED:
448 case PhoneConstants.APN_TYPE_NOT_AVAILABLE:
451 loge("Error in reconnect - unexpected response.");
458 * Turn on or off the mobile radio. No connectivity will be possible while the
459 * radio is off. The operation is a no-op if the radio is already in the desired state.
460 * @param turnOn {@code true} if the radio should be turned on, {@code false} if
462 public boolean setRadio(boolean turnOn) {
463 getPhoneService(false);
465 * If the phone process has crashed in the past, we'll get a
466 * RemoteException and need to re-reference the service.
468 for (int retry = 0; retry < 2; retry++) {
469 if (mPhoneService == null) {
470 loge("Ignoring mobile radio request because could not acquire PhoneService");
475 return mPhoneService.setRadio(turnOn);
476 } catch (RemoteException e) {
477 if (retry == 0) getPhoneService(true);
481 loge("Could not set radio power to " + (turnOn ? "on" : "off"));
486 public void setUserDataEnable(boolean enabled) {
487 if (DBG) log("setUserDataEnable: E enabled=" + enabled);
488 final AsyncChannel channel = mDataConnectionTrackerAc;
489 if (channel != null) {
490 channel.sendMessage(DctConstants.CMD_SET_USER_DATA_ENABLE,
491 enabled ? DctConstants.ENABLED : DctConstants.DISABLED);
492 mUserDataEnabled = enabled;
494 if (VDBG) log("setUserDataEnable: X enabled=" + enabled);
498 public void setPolicyDataEnable(boolean enabled) {
499 if (DBG) log("setPolicyDataEnable(enabled=" + enabled + ")");
500 final AsyncChannel channel = mDataConnectionTrackerAc;
501 if (channel != null) {
502 channel.sendMessage(DctConstants.CMD_SET_POLICY_DATA_ENABLE,
503 enabled ? DctConstants.ENABLED : DctConstants.DISABLED);
504 mPolicyDataEnabled = enabled;
509 * Eanble/disable FailFast
511 * @param enabled is DctConstants.ENABLED/DISABLED
513 public void setEnableFailFastMobileData(int enabled) {
514 if (DBG) log("setEnableFailFastMobileData(enabled=" + enabled + ")");
515 final AsyncChannel channel = mDataConnectionTrackerAc;
516 if (channel != null) {
517 channel.sendMessage(DctConstants.CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA, enabled);
522 * carrier dependency is met/unmet
525 public void setDependencyMet(boolean met) {
526 Bundle bundle = Bundle.forPair(DctConstants.APN_TYPE_KEY, mApnType);
528 if (DBG) log("setDependencyMet: E met=" + met);
529 Message msg = Message.obtain();
530 msg.what = DctConstants.CMD_SET_DEPENDENCY_MET;
531 msg.arg1 = (met ? DctConstants.ENABLED : DctConstants.DISABLED);
533 mDataConnectionTrackerAc.sendMessage(msg);
534 if (VDBG) log("setDependencyMet: X met=" + met);
535 } catch (NullPointerException e) {
536 loge("setDependencyMet: X mAc was null" + e);
541 public void addStackedLink(LinkProperties link) {
542 mLinkProperties.addStackedLink(link);
546 public void removeStackedLink(LinkProperties link) {
547 mLinkProperties.removeStackedLink(link);
551 public String toString() {
552 final CharArrayWriter writer = new CharArrayWriter();
553 final PrintWriter pw = new PrintWriter(writer);
554 pw.print("Mobile data state: "); pw.println(mMobileDataState);
555 pw.print("Data enabled: user="); pw.print(mUserDataEnabled);
556 pw.print(", policy="); pw.println(mPolicyDataEnabled);
557 return writer.toString();
561 * Internal method supporting the ENABLE_MMS feature.
562 * @param apnType the type of APN to be enabled or disabled (e.g., mms)
563 * @param enable {@code true} to enable the specified APN type,
564 * {@code false} to disable it.
565 * @return an integer value representing the outcome of the request.
567 private int setEnableApn(String apnType, boolean enable) {
568 getPhoneService(false);
570 * If the phone process has crashed in the past, we'll get a
571 * RemoteException and need to re-reference the service.
573 for (int retry = 0; retry < 2; retry++) {
574 if (mPhoneService == null) {
575 loge("Ignoring feature request because could not acquire PhoneService");
581 return mPhoneService.enableApnType(apnType);
583 return mPhoneService.disableApnType(apnType);
585 } catch (RemoteException e) {
586 if (retry == 0) getPhoneService(true);
590 loge("Could not " + (enable ? "enable" : "disable") + " APN type \"" + apnType + "\"");
591 return PhoneConstants.APN_REQUEST_FAILED;
594 public static String networkTypeToApnType(int netType) {
596 case ConnectivityManager.TYPE_MOBILE:
597 return PhoneConstants.APN_TYPE_DEFAULT; // TODO - use just one of these
598 case ConnectivityManager.TYPE_MOBILE_MMS:
599 return PhoneConstants.APN_TYPE_MMS;
600 case ConnectivityManager.TYPE_MOBILE_SUPL:
601 return PhoneConstants.APN_TYPE_SUPL;
602 case ConnectivityManager.TYPE_MOBILE_DUN:
603 return PhoneConstants.APN_TYPE_DUN;
604 case ConnectivityManager.TYPE_MOBILE_HIPRI:
605 return PhoneConstants.APN_TYPE_HIPRI;
606 case ConnectivityManager.TYPE_MOBILE_FOTA:
607 return PhoneConstants.APN_TYPE_FOTA;
608 case ConnectivityManager.TYPE_MOBILE_IMS:
609 return PhoneConstants.APN_TYPE_IMS;
610 case ConnectivityManager.TYPE_MOBILE_CBS:
611 return PhoneConstants.APN_TYPE_CBS;
613 sloge("Error mapping networkType " + netType + " to apnType.");
619 * @see android.net.NetworkStateTracker#getLinkProperties()
621 public LinkProperties getLinkProperties() {
622 return new LinkProperties(mLinkProperties);
626 * @see android.net.NetworkStateTracker#getLinkCapabilities()
628 public LinkCapabilities getLinkCapabilities() {
629 return new LinkCapabilities(mLinkCapabilities);
632 public void supplyMessenger(Messenger messenger) {
633 if (VDBG) log(mApnType + " got supplyMessenger");
634 AsyncChannel ac = new AsyncChannel();
635 ac.connect(mContext, MobileDataStateTracker.this.mHandler, messenger);
638 private void log(String s) {
639 Slog.d(TAG, mApnType + ": " + s);
642 private void loge(String s) {
643 Slog.e(TAG, mApnType + ": " + s);
646 static private void sloge(String s) {