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