MobileDataStateTracker.java revision d55a6b498d66d8fc415908ecf63e50f46cce67e8
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.Bundle;
24import android.os.HandlerThread;
25import android.os.Looper;
26import android.os.Messenger;
27import android.os.RemoteException;
28import android.os.Handler;
29import android.os.IBinder;
30import android.os.Message;
31import android.os.ServiceManager;
32
33import com.android.internal.telephony.DataConnectionTracker;
34import com.android.internal.telephony.ITelephony;
35import com.android.internal.telephony.Phone;
36import com.android.internal.telephony.TelephonyIntents;
37import com.android.internal.util.AsyncChannel;
38
39import android.net.NetworkInfo.DetailedState;
40import android.net.NetworkInfo;
41import android.net.LinkProperties;
42import android.telephony.TelephonyManager;
43import android.util.Slog;
44import android.text.TextUtils;
45
46/**
47 * Track the state of mobile data connectivity. This is done by
48 * receiving broadcast intents from the Phone process whenever
49 * the state of data connectivity changes.
50 *
51 * {@hide}
52 */
53public class MobileDataStateTracker implements NetworkStateTracker {
54
55    private static final String TAG = "MobileDataStateTracker";
56    private static final boolean DBG = true;
57    private static final boolean VDBG = false;
58
59    private Phone.DataState mMobileDataState;
60    private ITelephony mPhoneService;
61
62    private String mApnType;
63    private NetworkInfo mNetworkInfo;
64    private boolean mTeardownRequested = false;
65    private Handler mTarget;
66    private Context mContext;
67    private LinkProperties mLinkProperties;
68    private LinkCapabilities mLinkCapabilities;
69    private boolean mPrivateDnsRouteSet = false;
70    private boolean mDefaultRouteSet = false;
71
72    // DEFAULT and HIPRI are the same connection.  If we're one of these we need to check if
73    // the other is also disconnected before we reset sockets
74    private boolean mIsDefaultOrHipri = false;
75
76    private Handler mHandler;
77    private AsyncChannel mDataConnectionTrackerAc;
78    private Messenger mMessenger;
79
80    /**
81     * Create a new MobileDataStateTracker
82     * @param netType the ConnectivityManager network type
83     * @param tag the name of this network
84     */
85    public MobileDataStateTracker(int netType, String tag) {
86        mNetworkInfo = new NetworkInfo(netType,
87                TelephonyManager.getDefault().getNetworkType(), tag,
88                TelephonyManager.getDefault().getNetworkTypeName());
89        mApnType = networkTypeToApnType(netType);
90        if (netType == ConnectivityManager.TYPE_MOBILE ||
91                netType == ConnectivityManager.TYPE_MOBILE_HIPRI) {
92            mIsDefaultOrHipri = true;
93        }
94
95        mPhoneService = null;
96    }
97
98    /**
99     * Begin monitoring data connectivity.
100     *
101     * @param context is the current Android context
102     * @param target is the Hander to which to return the events.
103     */
104    public void startMonitoring(Context context, Handler target) {
105        mTarget = target;
106        mContext = context;
107
108        HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
109        handlerThread.start();
110        mHandler = new MdstHandler(handlerThread.getLooper(), this);
111
112        IntentFilter filter = new IntentFilter();
113        filter.addAction(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED);
114        filter.addAction(TelephonyIntents.ACTION_DATA_CONNECTION_FAILED);
115        filter.addAction(DataConnectionTracker.ACTION_DATA_CONNECTION_TRACKER_MESSENGER);
116
117        mContext.registerReceiver(new MobileDataStateReceiver(), filter);
118        mMobileDataState = Phone.DataState.DISCONNECTED;
119    }
120
121    static class MdstHandler extends Handler {
122        private MobileDataStateTracker mMdst;
123
124        MdstHandler(Looper looper, MobileDataStateTracker mdst) {
125            super(looper);
126            mMdst = mdst;
127        }
128
129        @Override
130        public void handleMessage(Message msg) {
131            switch (msg.what) {
132                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED:
133                    if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
134                        if (DBG) {
135                            mMdst.log("MdstHandler connected");
136                        }
137                        mMdst.mDataConnectionTrackerAc = (AsyncChannel) msg.obj;
138                    } else {
139                        if (DBG) {
140                            mMdst.log("MdstHandler %s NOT connected error=" + msg.arg1);
141                        }
142                    }
143                    break;
144                case AsyncChannel.CMD_CHANNEL_DISCONNECTED:
145                    mMdst.log("Disconnected from DataStateTracker");
146                    mMdst.mDataConnectionTrackerAc = null;
147                    break;
148                default: {
149                    mMdst.log("Ignorning unknown message=" + msg);
150                    break;
151                }
152            }
153        }
154    }
155
156    public boolean isPrivateDnsRouteSet() {
157        return mPrivateDnsRouteSet;
158    }
159
160    public void privateDnsRouteSet(boolean enabled) {
161        mPrivateDnsRouteSet = enabled;
162    }
163
164    public NetworkInfo getNetworkInfo() {
165        return mNetworkInfo;
166    }
167
168    public boolean isDefaultRouteSet() {
169        return mDefaultRouteSet;
170    }
171
172    public void defaultRouteSet(boolean enabled) {
173        mDefaultRouteSet = enabled;
174    }
175
176    /**
177     * This is not implemented.
178     */
179    public void releaseWakeLock() {
180    }
181
182    private class MobileDataStateReceiver extends BroadcastReceiver {
183        IConnectivityManager mConnectivityManager;
184
185        @Override
186        public void onReceive(Context context, Intent intent) {
187            if (intent.getAction().equals(TelephonyIntents.
188                    ACTION_ANY_DATA_CONNECTION_STATE_CHANGED)) {
189                String apnType = intent.getStringExtra(Phone.DATA_APN_TYPE_KEY);
190                if (VDBG) {
191                    log(String.format("Broadcast received: ACTION_ANY_DATA_CONNECTION_STATE_CHANGED"
192                        + "mApnType=%s %s received apnType=%s", mApnType,
193                        TextUtils.equals(apnType, mApnType) ? "==" : "!=", apnType));
194                }
195                if (!TextUtils.equals(apnType, mApnType)) {
196                    return;
197                }
198                mNetworkInfo.setSubtype(TelephonyManager.getDefault().getNetworkType(),
199                        TelephonyManager.getDefault().getNetworkTypeName());
200                Phone.DataState state = Enum.valueOf(Phone.DataState.class,
201                        intent.getStringExtra(Phone.STATE_KEY));
202                String reason = intent.getStringExtra(Phone.STATE_CHANGE_REASON_KEY);
203                String apnName = intent.getStringExtra(Phone.DATA_APN_KEY);
204
205                mNetworkInfo.setIsAvailable(!intent.getBooleanExtra(Phone.NETWORK_UNAVAILABLE_KEY,
206                        false));
207
208                if (DBG) {
209                    log("Received state=" + state + ", old=" + mMobileDataState +
210                        ", reason=" + (reason == null ? "(unspecified)" : reason));
211                }
212                if (mMobileDataState != state) {
213                    mMobileDataState = state;
214                    switch (state) {
215                        case DISCONNECTED:
216                            if(isTeardownRequested()) {
217                                setTeardownRequested(false);
218                            }
219
220                            setDetailedState(DetailedState.DISCONNECTED, reason, apnName);
221                            boolean doReset = true;
222                            if (mIsDefaultOrHipri == true) {
223                                // both default and hipri must go down before we reset
224                                int typeToCheck = (Phone.APN_TYPE_DEFAULT.equals(mApnType) ?
225                                    ConnectivityManager.TYPE_MOBILE_HIPRI :
226                                    ConnectivityManager.TYPE_MOBILE);
227                                if (mConnectivityManager == null) {
228                                    IBinder b = ServiceManager.getService(
229                                            Context.CONNECTIVITY_SERVICE);
230                                    mConnectivityManager = IConnectivityManager.Stub.asInterface(b);
231                                }
232                                try {
233                                    if (mConnectivityManager != null) {
234                                        NetworkInfo info = mConnectivityManager.getNetworkInfo(
235                                                typeToCheck);
236                                        if (info.isConnected() == true) {
237                                            doReset = false;
238                                        }
239                                    }
240                                } catch (RemoteException e) {
241                                    // just go ahead with the reset
242                                    loge("Exception trying to contact ConnService: " + e);
243                                }
244                            }
245                            if (doReset && mLinkProperties != null) {
246                                String iface = mLinkProperties.getInterfaceName();
247                                if (iface != null) NetworkUtils.resetConnections(iface);
248                            }
249                            // TODO - check this
250                            // can't do this here - ConnectivityService needs it to clear stuff
251                            // it's ok though - just leave it to be refreshed next time
252                            // we connect.
253                            //if (DBG) log("clearing mInterfaceName for "+ mApnType +
254                            //        " as it DISCONNECTED");
255                            //mInterfaceName = null;
256                            break;
257                        case CONNECTING:
258                            setDetailedState(DetailedState.CONNECTING, reason, apnName);
259                            break;
260                        case SUSPENDED:
261                            setDetailedState(DetailedState.SUSPENDED, reason, apnName);
262                            break;
263                        case CONNECTED:
264                            mLinkProperties = intent.getParcelableExtra(
265                                    Phone.DATA_LINK_PROPERTIES_KEY);
266                            if (mLinkProperties == null) {
267                                log("CONNECTED event did not supply link properties.");
268                                mLinkProperties = new LinkProperties();
269                            }
270                            mLinkCapabilities = intent.getParcelableExtra(
271                                    Phone.DATA_LINK_CAPABILITIES_KEY);
272                            if (mLinkCapabilities == null) {
273                                log("CONNECTED event did not supply link capabilities.");
274                                mLinkCapabilities = new LinkCapabilities();
275                            }
276                            setDetailedState(DetailedState.CONNECTED, reason, apnName);
277                            break;
278                    }
279                }
280            } else if (intent.getAction().
281                    equals(TelephonyIntents.ACTION_DATA_CONNECTION_FAILED)) {
282                String apnType = intent.getStringExtra(Phone.DATA_APN_TYPE_KEY);
283                if (!TextUtils.equals(apnType, mApnType)) {
284                    if (DBG) {
285                        log(String.format(
286                                "Broadcast received: ACTION_ANY_DATA_CONNECTION_FAILED ignore, " +
287                                "mApnType=%s != received apnType=%s", mApnType, apnType));
288                    }
289                    return;
290                }
291                String reason = intent.getStringExtra(Phone.FAILURE_REASON_KEY);
292                String apnName = intent.getStringExtra(Phone.DATA_APN_KEY);
293                if (DBG) {
294                    log("Received " + intent.getAction() +
295                                " broadcast" + reason == null ? "" : "(" + reason + ")");
296                }
297                setDetailedState(DetailedState.FAILED, reason, apnName);
298            } else if (intent.getAction().
299                    equals(DataConnectionTracker.ACTION_DATA_CONNECTION_TRACKER_MESSENGER)) {
300                if (DBG) log(mApnType + " got ACTION_DATA_CONNECTION_TRACKER_MESSENGER");
301                mMessenger = intent.getParcelableExtra(DataConnectionTracker.EXTRA_MESSENGER);
302                AsyncChannel ac = new AsyncChannel();
303                ac.connect(mContext, MobileDataStateTracker.this.mHandler, mMessenger);
304            } else {
305                if (DBG) log("Broadcast received: ignore " + intent.getAction());
306            }
307        }
308    }
309
310    private void getPhoneService(boolean forceRefresh) {
311        if ((mPhoneService == null) || forceRefresh) {
312            mPhoneService = ITelephony.Stub.asInterface(ServiceManager.getService("phone"));
313        }
314    }
315
316    /**
317     * Report whether data connectivity is possible.
318     */
319    public boolean isAvailable() {
320        return mNetworkInfo.isAvailable();
321    }
322
323    /**
324     * Return the system properties name associated with the tcp buffer sizes
325     * for this network.
326     */
327    public String getTcpBufferSizesPropName() {
328        String networkTypeStr = "unknown";
329        TelephonyManager tm = new TelephonyManager(mContext);
330        //TODO We have to edit the parameter for getNetworkType regarding CDMA
331        switch(tm.getNetworkType()) {
332        case TelephonyManager.NETWORK_TYPE_GPRS:
333            networkTypeStr = "gprs";
334            break;
335        case TelephonyManager.NETWORK_TYPE_EDGE:
336            networkTypeStr = "edge";
337            break;
338        case TelephonyManager.NETWORK_TYPE_UMTS:
339            networkTypeStr = "umts";
340            break;
341        case TelephonyManager.NETWORK_TYPE_HSDPA:
342            networkTypeStr = "hsdpa";
343            break;
344        case TelephonyManager.NETWORK_TYPE_HSUPA:
345            networkTypeStr = "hsupa";
346            break;
347        case TelephonyManager.NETWORK_TYPE_HSPA:
348            networkTypeStr = "hspa";
349            break;
350        case TelephonyManager.NETWORK_TYPE_CDMA:
351            networkTypeStr = "cdma";
352            break;
353        case TelephonyManager.NETWORK_TYPE_1xRTT:
354            networkTypeStr = "1xrtt";
355            break;
356        case TelephonyManager.NETWORK_TYPE_EVDO_0:
357            networkTypeStr = "evdo";
358            break;
359        case TelephonyManager.NETWORK_TYPE_EVDO_A:
360            networkTypeStr = "evdo";
361            break;
362        case TelephonyManager.NETWORK_TYPE_EVDO_B:
363            networkTypeStr = "evdo";
364            break;
365        case TelephonyManager.NETWORK_TYPE_IDEN:
366            networkTypeStr = "iden";
367            break;
368        case TelephonyManager.NETWORK_TYPE_LTE:
369            networkTypeStr = "lte";
370            break;
371        case TelephonyManager.NETWORK_TYPE_EHRPD:
372            networkTypeStr = "ehrpd";
373            break;
374        default:
375            loge("unknown network type: " + tm.getNetworkType());
376        }
377        return "net.tcp.buffersize." + networkTypeStr;
378    }
379
380    /**
381     * Tear down mobile data connectivity, i.e., disable the ability to create
382     * mobile data connections.
383     * TODO - make async and return nothing?
384     */
385    public boolean teardown() {
386        setTeardownRequested(true);
387        return (setEnableApn(mApnType, false) != Phone.APN_REQUEST_FAILED);
388    }
389
390    /**
391     * Record the detailed state of a network, and if it is a
392     * change from the previous state, send a notification to
393     * any listeners.
394     * @param state the new @{code DetailedState}
395     * @param reason a {@code String} indicating a reason for the state change,
396     * if one was supplied. May be {@code null}.
397     * @param extraInfo optional {@code String} providing extra information about the state change
398     */
399    private void setDetailedState(NetworkInfo.DetailedState state, String reason,
400            String extraInfo) {
401        if (DBG) log("setDetailed state, old ="
402                + mNetworkInfo.getDetailedState() + " and new state=" + state);
403        if (state != mNetworkInfo.getDetailedState()) {
404            boolean wasConnecting = (mNetworkInfo.getState() == NetworkInfo.State.CONNECTING);
405            String lastReason = mNetworkInfo.getReason();
406            /*
407             * If a reason was supplied when the CONNECTING state was entered, and no
408             * reason was supplied for entering the CONNECTED state, then retain the
409             * reason that was supplied when going to CONNECTING.
410             */
411            if (wasConnecting && state == NetworkInfo.DetailedState.CONNECTED && reason == null
412                    && lastReason != null)
413                reason = lastReason;
414            mNetworkInfo.setDetailedState(state, reason, extraInfo);
415            Message msg = mTarget.obtainMessage(EVENT_STATE_CHANGED, mNetworkInfo);
416            msg.sendToTarget();
417        }
418    }
419
420    public void setTeardownRequested(boolean isRequested) {
421        mTeardownRequested = isRequested;
422    }
423
424    public boolean isTeardownRequested() {
425        return mTeardownRequested;
426    }
427
428    /**
429     * Re-enable mobile data connectivity after a {@link #teardown()}.
430     * TODO - make async and always get a notification?
431     */
432    public boolean reconnect() {
433        boolean retValue = false; //connected or expect to be?
434        setTeardownRequested(false);
435        switch (setEnableApn(mApnType, true)) {
436            case Phone.APN_ALREADY_ACTIVE:
437                // need to set self to CONNECTING so the below message is handled.
438                retValue = true;
439                break;
440            case Phone.APN_REQUEST_STARTED:
441                // set IDLE here , avoid the following second FAILED not sent out
442                mNetworkInfo.setDetailedState(DetailedState.IDLE, null, null);
443                retValue = true;
444                break;
445            case Phone.APN_REQUEST_FAILED:
446            case Phone.APN_TYPE_NOT_AVAILABLE:
447                break;
448            default:
449                loge("Error in reconnect - unexpected response.");
450                break;
451        }
452        return retValue;
453    }
454
455    /**
456     * Turn on or off the mobile radio. No connectivity will be possible while the
457     * radio is off. The operation is a no-op if the radio is already in the desired state.
458     * @param turnOn {@code true} if the radio should be turned on, {@code false} if
459     */
460    public boolean setRadio(boolean turnOn) {
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("Ignoring mobile radio request because could not acquire PhoneService");
469                break;
470            }
471
472            try {
473                return mPhoneService.setRadio(turnOn);
474            } catch (RemoteException e) {
475                if (retry == 0) getPhoneService(true);
476            }
477        }
478
479        log("Could not set radio power to " + (turnOn ? "on" : "off"));
480        return false;
481    }
482
483    /**
484     * @param enabled
485     */
486    public void setDataEnable(boolean enabled) {
487        try {
488            log("setDataEnable: E enabled=" + enabled);
489            mDataConnectionTrackerAc.sendMessage(DataConnectionTracker.CMD_SET_DATA_ENABLE,
490                    enabled ? DataConnectionTracker.ENABLED : DataConnectionTracker.DISABLED);
491            log("setDataEnable: X enabled=" + enabled);
492        } catch (Exception e) {
493            log("setDataEnable: X mAc was null" + e);
494        }
495    }
496
497    /**
498     * carrier dependency is met/unmet
499     * @param met
500     */
501    public void setDependencyMet(boolean met) {
502        Bundle bundle = Bundle.forPair(DataConnectionTracker.APN_TYPE_KEY, mApnType);
503        try {
504            log("setDependencyMet: E met=" + met);
505            Message msg = Message.obtain();
506            msg.what = DataConnectionTracker.CMD_SET_DEPENDENCY_MET;
507            msg.arg1 = (met ? DataConnectionTracker.ENABLED : DataConnectionTracker.DISABLED);
508            msg.setData(bundle);
509            mDataConnectionTrackerAc.sendMessage(msg);
510            log("setDependencyMet: X met=" + met);
511        } catch (NullPointerException e) {
512            log("setDependencyMet: X mAc was null" + e);
513        }
514    }
515
516    @Override
517    public String toString() {
518        StringBuffer sb = new StringBuffer("Mobile data state: ");
519
520        sb.append(mMobileDataState);
521        return sb.toString();
522    }
523
524   /**
525     * Internal method supporting the ENABLE_MMS feature.
526     * @param apnType the type of APN to be enabled or disabled (e.g., mms)
527     * @param enable {@code true} to enable the specified APN type,
528     * {@code false} to disable it.
529     * @return an integer value representing the outcome of the request.
530     */
531    private int setEnableApn(String apnType, boolean enable) {
532        getPhoneService(false);
533        /*
534         * If the phone process has crashed in the past, we'll get a
535         * RemoteException and need to re-reference the service.
536         */
537        for (int retry = 0; retry < 2; retry++) {
538            if (mPhoneService == null) {
539                log("Ignoring feature request because could not acquire PhoneService");
540                break;
541            }
542
543            try {
544                if (enable) {
545                    return mPhoneService.enableApnType(apnType);
546                } else {
547                    return mPhoneService.disableApnType(apnType);
548                }
549            } catch (RemoteException e) {
550                if (retry == 0) getPhoneService(true);
551            }
552        }
553
554        log("Could not " + (enable ? "enable" : "disable") + " APN type \"" + apnType + "\"");
555        return Phone.APN_REQUEST_FAILED;
556    }
557
558    public static String networkTypeToApnType(int netType) {
559        switch(netType) {
560            case ConnectivityManager.TYPE_MOBILE:
561                return Phone.APN_TYPE_DEFAULT;  // TODO - use just one of these
562            case ConnectivityManager.TYPE_MOBILE_MMS:
563                return Phone.APN_TYPE_MMS;
564            case ConnectivityManager.TYPE_MOBILE_SUPL:
565                return Phone.APN_TYPE_SUPL;
566            case ConnectivityManager.TYPE_MOBILE_DUN:
567                return Phone.APN_TYPE_DUN;
568            case ConnectivityManager.TYPE_MOBILE_HIPRI:
569                return Phone.APN_TYPE_HIPRI;
570            case ConnectivityManager.TYPE_MOBILE_FOTA:
571                return Phone.APN_TYPE_FOTA;
572            case ConnectivityManager.TYPE_MOBILE_IMS:
573                return Phone.APN_TYPE_IMS;
574            case ConnectivityManager.TYPE_MOBILE_CBS:
575                return Phone.APN_TYPE_CBS;
576            default:
577                sloge("Error mapping networkType " + netType + " to apnType.");
578                return null;
579        }
580    }
581
582    /**
583     * @see android.net.NetworkStateTracker#getLinkProperties()
584     */
585    public LinkProperties getLinkProperties() {
586        return new LinkProperties(mLinkProperties);
587    }
588
589    /**
590     * @see android.net.NetworkStateTracker#getLinkCapabilities()
591     */
592    public LinkCapabilities getLinkCapabilities() {
593        return new LinkCapabilities(mLinkCapabilities);
594    }
595
596    private void log(String s) {
597        Slog.d(TAG, mApnType + ": " + s);
598    }
599
600    private void loge(String s) {
601        Slog.e(TAG, mApnType + ": " + s);
602    }
603
604    static private void sloge(String s) {
605        Slog.e(TAG, s);
606    }
607}
608