MobileDataStateTracker.java revision c9acde9aa6cf21598640aeebb7d908f1926a48dd
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 static com.android.internal.telephony.DataConnectionTracker.CMD_SET_POLICY_DATA_ENABLE;
20import static com.android.internal.telephony.DataConnectionTracker.CMD_SET_USER_DATA_ENABLE;
21import static com.android.internal.telephony.DataConnectionTracker.DISABLED;
22import static com.android.internal.telephony.DataConnectionTracker.ENABLED;
23
24import android.content.BroadcastReceiver;
25import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
28import android.net.NetworkInfo.DetailedState;
29import android.os.Bundle;
30import android.os.Handler;
31import android.os.Looper;
32import android.os.Message;
33import android.os.Messenger;
34import android.os.RemoteException;
35import android.os.ServiceManager;
36import android.telephony.TelephonyManager;
37import android.text.TextUtils;
38import android.util.Slog;
39
40import com.android.internal.telephony.DataConnectionTracker;
41import com.android.internal.telephony.ITelephony;
42import com.android.internal.telephony.Phone;
43import com.android.internal.telephony.TelephonyIntents;
44import com.android.internal.util.AsyncChannel;
45
46import java.io.CharArrayWriter;
47import java.io.PrintWriter;
48
49/**
50 * Track the state of mobile data connectivity. This is done by
51 * receiving broadcast intents from the Phone process whenever
52 * the state of data connectivity changes.
53 *
54 * {@hide}
55 */
56public class MobileDataStateTracker implements NetworkStateTracker {
57
58    private static final String TAG = "MobileDataStateTracker";
59    private static final boolean DBG = false;
60    private static final boolean VDBG = false;
61
62    private Phone.DataState mMobileDataState;
63    private ITelephony mPhoneService;
64
65    private String mApnType;
66    private NetworkInfo mNetworkInfo;
67    private boolean mTeardownRequested = false;
68    private Handler mTarget;
69    private Context mContext;
70    private LinkProperties mLinkProperties;
71    private LinkCapabilities mLinkCapabilities;
72    private boolean mPrivateDnsRouteSet = false;
73    private boolean mDefaultRouteSet = false;
74
75    // NOTE: these are only kept for debugging output; actual values are
76    // maintained in DataConnectionTracker.
77    protected boolean mUserDataEnabled = true;
78    protected boolean mPolicyDataEnabled = true;
79
80    private Handler mHandler;
81    private AsyncChannel mDataConnectionTrackerAc;
82    private Messenger mMessenger;
83
84    /**
85     * Create a new MobileDataStateTracker
86     * @param netType the ConnectivityManager network type
87     * @param tag the name of this network
88     */
89    public MobileDataStateTracker(int netType, String tag) {
90        mNetworkInfo = new NetworkInfo(netType,
91                TelephonyManager.getDefault().getNetworkType(), tag,
92                TelephonyManager.getDefault().getNetworkTypeName());
93        mApnType = networkTypeToApnType(netType);
94    }
95
96    /**
97     * Begin monitoring data connectivity.
98     *
99     * @param context is the current Android context
100     * @param target is the Hander to which to return the events.
101     */
102    public void startMonitoring(Context context, Handler target) {
103        mTarget = target;
104        mContext = context;
105
106        mHandler = new MdstHandler(target.getLooper(), this);
107
108        IntentFilter filter = new IntentFilter();
109        filter.addAction(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED);
110        filter.addAction(TelephonyIntents.ACTION_DATA_CONNECTION_FAILED);
111        filter.addAction(DataConnectionTracker.ACTION_DATA_CONNECTION_TRACKER_MESSENGER);
112
113        mContext.registerReceiver(new MobileDataStateReceiver(), filter);
114        mMobileDataState = Phone.DataState.DISCONNECTED;
115    }
116
117    static class MdstHandler extends Handler {
118        private MobileDataStateTracker mMdst;
119
120        MdstHandler(Looper looper, MobileDataStateTracker mdst) {
121            super(looper);
122            mMdst = mdst;
123        }
124
125        @Override
126        public void handleMessage(Message msg) {
127            switch (msg.what) {
128                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED:
129                    if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
130                        if (VDBG) {
131                            mMdst.log("MdstHandler connected");
132                        }
133                        mMdst.mDataConnectionTrackerAc = (AsyncChannel) msg.obj;
134                    } else {
135                        if (VDBG) {
136                            mMdst.log("MdstHandler %s NOT connected error=" + msg.arg1);
137                        }
138                    }
139                    break;
140                case AsyncChannel.CMD_CHANNEL_DISCONNECTED:
141                    if (VDBG) mMdst.log("Disconnected from DataStateTracker");
142                    mMdst.mDataConnectionTrackerAc = null;
143                    break;
144                default: {
145                    if (VDBG) mMdst.log("Ignorning unknown message=" + msg);
146                    break;
147                }
148            }
149        }
150    }
151
152    public boolean isPrivateDnsRouteSet() {
153        return mPrivateDnsRouteSet;
154    }
155
156    public void privateDnsRouteSet(boolean enabled) {
157        mPrivateDnsRouteSet = enabled;
158    }
159
160    public NetworkInfo getNetworkInfo() {
161        return mNetworkInfo;
162    }
163
164    public boolean isDefaultRouteSet() {
165        return mDefaultRouteSet;
166    }
167
168    public void defaultRouteSet(boolean enabled) {
169        mDefaultRouteSet = enabled;
170    }
171
172    /**
173     * This is not implemented.
174     */
175    public void releaseWakeLock() {
176    }
177
178    private class MobileDataStateReceiver extends BroadcastReceiver {
179        @Override
180        public void onReceive(Context context, Intent intent) {
181            if (intent.getAction().equals(TelephonyIntents.
182                    ACTION_ANY_DATA_CONNECTION_STATE_CHANGED)) {
183                String apnType = intent.getStringExtra(Phone.DATA_APN_TYPE_KEY);
184                if (VDBG) {
185                    log(String.format("Broadcast received: ACTION_ANY_DATA_CONNECTION_STATE_CHANGED"
186                        + "mApnType=%s %s received apnType=%s", mApnType,
187                        TextUtils.equals(apnType, mApnType) ? "==" : "!=", apnType));
188                }
189                if (!TextUtils.equals(apnType, mApnType)) {
190                    return;
191                }
192                mNetworkInfo.setSubtype(TelephonyManager.getDefault().getNetworkType(),
193                        TelephonyManager.getDefault().getNetworkTypeName());
194                Phone.DataState state = Enum.valueOf(Phone.DataState.class,
195                        intent.getStringExtra(Phone.STATE_KEY));
196                String reason = intent.getStringExtra(Phone.STATE_CHANGE_REASON_KEY);
197                String apnName = intent.getStringExtra(Phone.DATA_APN_KEY);
198                mNetworkInfo.setRoaming(intent.getBooleanExtra(Phone.DATA_NETWORK_ROAMING_KEY,
199                        false));
200
201                mNetworkInfo.setIsAvailable(!intent.getBooleanExtra(Phone.NETWORK_UNAVAILABLE_KEY,
202                        false));
203
204                if (DBG) {
205                    log("Received state=" + state + ", old=" + mMobileDataState +
206                        ", reason=" + (reason == null ? "(unspecified)" : reason));
207                }
208                if (mMobileDataState != state) {
209                    mMobileDataState = state;
210                    switch (state) {
211                        case DISCONNECTED:
212                            if(isTeardownRequested()) {
213                                setTeardownRequested(false);
214                            }
215
216                            setDetailedState(DetailedState.DISCONNECTED, reason, apnName);
217                            // can't do this here - ConnectivityService needs it to clear stuff
218                            // it's ok though - just leave it to be refreshed next time
219                            // we connect.
220                            //if (DBG) log("clearing mInterfaceName for "+ mApnType +
221                            //        " as it DISCONNECTED");
222                            //mInterfaceName = null;
223                            break;
224                        case CONNECTING:
225                            setDetailedState(DetailedState.CONNECTING, reason, apnName);
226                            break;
227                        case SUSPENDED:
228                            setDetailedState(DetailedState.SUSPENDED, reason, apnName);
229                            break;
230                        case CONNECTED:
231                            mLinkProperties = intent.getParcelableExtra(
232                                    Phone.DATA_LINK_PROPERTIES_KEY);
233                            if (mLinkProperties == null) {
234                                loge("CONNECTED event did not supply link properties.");
235                                mLinkProperties = new LinkProperties();
236                            }
237                            mLinkCapabilities = intent.getParcelableExtra(
238                                    Phone.DATA_LINK_CAPABILITIES_KEY);
239                            if (mLinkCapabilities == null) {
240                                loge("CONNECTED event did not supply link capabilities.");
241                                mLinkCapabilities = new LinkCapabilities();
242                            }
243                            setDetailedState(DetailedState.CONNECTED, reason, apnName);
244                            break;
245                    }
246                } else {
247                    // There was no state change. Check if LinkProperties has been updated.
248                    if (TextUtils.equals(reason, Phone.REASON_LINK_PROPERTIES_CHANGED)) {
249                        mLinkProperties = intent.getParcelableExtra(Phone.DATA_LINK_PROPERTIES_KEY);
250                        if (mLinkProperties == null) {
251                            loge("No link property in LINK_PROPERTIES change event.");
252                            mLinkProperties = new LinkProperties();
253                        }
254                        // Just update reason field in this NetworkInfo
255                        mNetworkInfo.setDetailedState(mNetworkInfo.getDetailedState(), reason,
256                                                      mNetworkInfo.getExtraInfo());
257                        Message msg = mTarget.obtainMessage(EVENT_CONFIGURATION_CHANGED,
258                                                            mNetworkInfo);
259                        msg.sendToTarget();
260                    }
261                }
262            } else if (intent.getAction().
263                    equals(TelephonyIntents.ACTION_DATA_CONNECTION_FAILED)) {
264                String apnType = intent.getStringExtra(Phone.DATA_APN_TYPE_KEY);
265                if (!TextUtils.equals(apnType, mApnType)) {
266                    if (DBG) {
267                        log(String.format(
268                                "Broadcast received: ACTION_ANY_DATA_CONNECTION_FAILED ignore, " +
269                                "mApnType=%s != received apnType=%s", mApnType, apnType));
270                    }
271                    return;
272                }
273                String reason = intent.getStringExtra(Phone.FAILURE_REASON_KEY);
274                String apnName = intent.getStringExtra(Phone.DATA_APN_KEY);
275                if (DBG) {
276                    log("Received " + intent.getAction() +
277                                " broadcast" + reason == null ? "" : "(" + reason + ")");
278                }
279                setDetailedState(DetailedState.FAILED, reason, apnName);
280            } else if (intent.getAction().
281                    equals(DataConnectionTracker.ACTION_DATA_CONNECTION_TRACKER_MESSENGER)) {
282                if (VDBG) log(mApnType + " got ACTION_DATA_CONNECTION_TRACKER_MESSENGER");
283                mMessenger = intent.getParcelableExtra(DataConnectionTracker.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) != Phone.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 Phone.APN_ALREADY_ACTIVE:
419                // need to set self to CONNECTING so the below message is handled.
420                retValue = true;
421                break;
422            case Phone.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 Phone.APN_REQUEST_FAILED:
428            case Phone.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(CMD_SET_USER_DATA_ENABLE, enabled ? ENABLED : DISABLED);
471            mUserDataEnabled = enabled;
472        }
473        if (VDBG) log("setUserDataEnable: X enabled=" + enabled);
474    }
475
476    @Override
477    public void setPolicyDataEnable(boolean enabled) {
478        if (DBG) log("setPolicyDataEnable(enabled=" + enabled + ")");
479        final AsyncChannel channel = mDataConnectionTrackerAc;
480        if (channel != null) {
481            channel.sendMessage(CMD_SET_POLICY_DATA_ENABLE, enabled ? ENABLED : DISABLED);
482            mPolicyDataEnabled = enabled;
483        }
484    }
485
486    /**
487     * carrier dependency is met/unmet
488     * @param met
489     */
490    public void setDependencyMet(boolean met) {
491        Bundle bundle = Bundle.forPair(DataConnectionTracker.APN_TYPE_KEY, mApnType);
492        try {
493            if (DBG) log("setDependencyMet: E met=" + met);
494            Message msg = Message.obtain();
495            msg.what = DataConnectionTracker.CMD_SET_DEPENDENCY_MET;
496            msg.arg1 = (met ? DataConnectionTracker.ENABLED : DataConnectionTracker.DISABLED);
497            msg.setData(bundle);
498            mDataConnectionTrackerAc.sendMessage(msg);
499            if (VDBG) log("setDependencyMet: X met=" + met);
500        } catch (NullPointerException e) {
501            loge("setDependencyMet: X mAc was null" + e);
502        }
503    }
504
505    @Override
506    public String toString() {
507        final CharArrayWriter writer = new CharArrayWriter();
508        final PrintWriter pw = new PrintWriter(writer);
509        pw.print("Mobile data state: "); pw.println(mMobileDataState);
510        pw.print("Data enabled: user="); pw.print(mUserDataEnabled);
511        pw.print(", policy="); pw.println(mPolicyDataEnabled);
512        return writer.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                loge("Ignoring feature request because could not acquire PhoneService");
531                break;
532            }
533
534            try {
535                if (enable) {
536                    return mPhoneService.enableApnType(apnType);
537                } else {
538                    return mPhoneService.disableApnType(apnType);
539                }
540            } catch (RemoteException e) {
541                if (retry == 0) getPhoneService(true);
542            }
543        }
544
545        loge("Could not " + (enable ? "enable" : "disable") + " APN type \"" + apnType + "\"");
546        return Phone.APN_REQUEST_FAILED;
547    }
548
549    public static String networkTypeToApnType(int netType) {
550        switch(netType) {
551            case ConnectivityManager.TYPE_MOBILE:
552                return Phone.APN_TYPE_DEFAULT;  // TODO - use just one of these
553            case ConnectivityManager.TYPE_MOBILE_MMS:
554                return Phone.APN_TYPE_MMS;
555            case ConnectivityManager.TYPE_MOBILE_SUPL:
556                return Phone.APN_TYPE_SUPL;
557            case ConnectivityManager.TYPE_MOBILE_DUN:
558                return Phone.APN_TYPE_DUN;
559            case ConnectivityManager.TYPE_MOBILE_HIPRI:
560                return Phone.APN_TYPE_HIPRI;
561            case ConnectivityManager.TYPE_MOBILE_FOTA:
562                return Phone.APN_TYPE_FOTA;
563            case ConnectivityManager.TYPE_MOBILE_IMS:
564                return Phone.APN_TYPE_IMS;
565            case ConnectivityManager.TYPE_MOBILE_CBS:
566                return Phone.APN_TYPE_CBS;
567            default:
568                sloge("Error mapping networkType " + netType + " to apnType.");
569                return null;
570        }
571    }
572
573    /**
574     * @see android.net.NetworkStateTracker#getLinkProperties()
575     */
576    public LinkProperties getLinkProperties() {
577        return new LinkProperties(mLinkProperties);
578    }
579
580    /**
581     * @see android.net.NetworkStateTracker#getLinkCapabilities()
582     */
583    public LinkCapabilities getLinkCapabilities() {
584        return new LinkCapabilities(mLinkCapabilities);
585    }
586
587    private void log(String s) {
588        Slog.d(TAG, mApnType + ": " + s);
589    }
590
591    private void loge(String s) {
592        Slog.e(TAG, mApnType + ": " + s);
593    }
594
595    static private void sloge(String s) {
596        Slog.e(TAG, s);
597    }
598}
599