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