ConnectivityManagerTestActivity.java revision d3975a917799b85cacaf382b65c5832813066b51
1/*
2 * Copyright (C) 2010, 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 com.android.connectivitymanagertest;
18
19import android.app.Activity;
20import android.content.Context;
21import android.content.BroadcastReceiver;
22import android.content.Intent;
23import android.content.IntentFilter;
24import android.net.ConnectivityManager;
25import android.net.NetworkInfo;
26import android.net.NetworkInfo.State;
27import android.net.wifi.WifiConfiguration;
28import android.net.wifi.WifiManager;
29import android.net.wifi.WifiInfo;
30import android.net.wifi.ScanResult;
31import android.net.wifi.WifiConfiguration.KeyMgmt;
32import android.os.Bundle;
33import android.os.Handler;
34import android.os.IPowerManager;
35import android.os.Message;
36import android.os.PowerManager;
37import android.os.ServiceManager;
38import android.os.SystemClock;
39import android.provider.Settings;
40import android.util.Log;
41import android.view.KeyEvent;
42import android.widget.LinearLayout;
43
44import com.android.internal.util.AsyncChannel;
45
46import java.io.IOException;
47import java.io.InputStream;
48import java.net.UnknownHostException;
49import java.util.ArrayList;
50import java.util.List;
51
52
53/**
54 * An activity registered with connectivity manager broadcast
55 * provides network connectivity information and
56 * can be used to set device states: Cellular, Wifi, Airplane mode.
57 */
58public class ConnectivityManagerTestActivity extends Activity {
59
60    public static final String LOG_TAG = "ConnectivityManagerTestActivity";
61    public static final int WAIT_FOR_SCAN_RESULT = 10 * 1000; //10 seconds
62    public static final int WIFI_SCAN_TIMEOUT = 50 * 1000;
63    public static final int SHORT_TIMEOUT = 5 * 1000;
64    public static final long LONG_TIMEOUT = 50 * 1000;
65    // 2 minutes timer between wifi stop and start
66    public static final long  WIFI_STOP_START_INTERVAL = 2 * 60 * 1000;
67    public static final int SUCCESS = 0;  // for Wifi tethering state change
68    public static final int FAILURE = 1;
69    public static final int INIT = -1;
70    private static final String ACCESS_POINT_FILE = "accesspoints.xml";
71    public ConnectivityReceiver mConnectivityReceiver = null;
72    public WifiReceiver mWifiReceiver = null;
73    private AccessPointParserHelper mParseHelper = null;
74    /*
75     * Track network connectivity information
76     */
77    public State mState;
78    public NetworkInfo mNetworkInfo;
79    public NetworkInfo mOtherNetworkInfo;
80    public boolean mIsFailOver;
81    public String mReason;
82    public boolean mScanResultIsAvailable = false;
83    public ConnectivityManager mCM;
84    public Object wifiObject = new Object();
85    public Object connectivityObject = new Object();
86    public int mWifiState;
87    public NetworkInfo mWifiNetworkInfo;
88    public String mBssid;
89    public String mPowerSsid = "opennet"; //Default power SSID
90    private Context mContext;
91    public boolean scanResultAvailable = false;
92
93    /*
94     * Control Wifi States
95     */
96    public WifiManager mWifiManager;
97    public WifiManager.Channel mChannel;
98
99    /*
100     * Verify connectivity state
101     */
102    public static final int NUM_NETWORK_TYPES = ConnectivityManager.MAX_NETWORK_TYPE + 1;
103    NetworkState[] connectivityState = new NetworkState[NUM_NETWORK_TYPES];
104
105    // For wifi tethering tests
106    private String[] mWifiRegexs;
107    public int mWifiTetherResult = INIT;    // -1 is initialization state
108
109    /**
110     * A wrapper of a broadcast receiver which provides network connectivity information
111     * for all kinds of network: wifi, mobile, etc.
112     */
113    private class ConnectivityReceiver extends BroadcastReceiver {
114        @Override
115        public void onReceive(Context context, Intent intent) {
116            log("ConnectivityReceiver: onReceive() is called with " + intent);
117            String action = intent.getAction();
118            if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
119                Log.v("ConnectivityReceiver", "onReceive() called with " + intent);
120                return;
121            }
122
123            boolean noConnectivity =
124                intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
125
126            if (noConnectivity) {
127                mState = State.DISCONNECTED;
128            } else {
129                mState = State.CONNECTED;
130            }
131
132            mNetworkInfo = (NetworkInfo)
133                intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
134
135            mOtherNetworkInfo = (NetworkInfo)
136                intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
137
138            mReason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
139            mIsFailOver = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
140
141            log("mNetworkInfo: " + mNetworkInfo.toString());
142            if (mOtherNetworkInfo != null) {
143                log("mOtherNetworkInfo: " + mOtherNetworkInfo.toString());
144            }
145            recordNetworkState(mNetworkInfo.getType(), mNetworkInfo.getState());
146            if (mOtherNetworkInfo != null) {
147                recordNetworkState(mOtherNetworkInfo.getType(), mOtherNetworkInfo.getState());
148            }
149            notifyNetworkConnectivityChange();
150        }
151    }
152
153    private class WifiReceiver extends BroadcastReceiver {
154        @Override
155        public void onReceive(Context context, Intent intent) {
156            String action = intent.getAction();
157            Log.v("WifiReceiver", "onReceive() is calleld with " + intent);
158            if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
159                log("scan results are available");
160                notifyScanResult();
161            } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
162                mWifiNetworkInfo =
163                    (NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
164                log("mWifiNetworkInfo: " + mWifiNetworkInfo.toString());
165                if (mWifiNetworkInfo.getState() == State.CONNECTED) {
166                    mBssid = intent.getStringExtra(WifiManager.EXTRA_BSSID);
167                }
168                notifyWifiState();
169            } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
170                mWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
171                                                WifiManager.WIFI_STATE_UNKNOWN);
172                notifyWifiState();
173            } else if (action.equals(WifiManager.WIFI_AP_STATE_CHANGED_ACTION)) {
174                notifyWifiAPState();
175            } else if (action.equals(ConnectivityManager.ACTION_TETHER_STATE_CHANGED)) {
176                ArrayList<String> available = intent.getStringArrayListExtra(
177                        ConnectivityManager.EXTRA_AVAILABLE_TETHER);
178                ArrayList<String> active = intent.getStringArrayListExtra(
179                        ConnectivityManager.EXTRA_ACTIVE_TETHER);
180                ArrayList<String> errored = intent.getStringArrayListExtra(
181                        ConnectivityManager.EXTRA_ERRORED_TETHER);
182                updateTetherState(available.toArray(), active.toArray(), errored.toArray());
183            }
184            else {
185                return;
186            }
187        }
188    }
189
190    private class WifiServiceHandler extends Handler {
191        @Override
192        public void handleMessage(Message msg) {
193            switch (msg.what) {
194                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED:
195                    if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
196                        //AsyncChannel in msg.obj
197                    } else {
198                        log("Failed to establish AsyncChannel connection");
199                    }
200                    break;
201                default:
202                    //Ignore
203                    break;
204            }
205        }
206    }
207
208    public ConnectivityManagerTestActivity() {
209        mState = State.UNKNOWN;
210        scanResultAvailable = false;
211    }
212
213    @Override
214    protected void onCreate(Bundle savedInstanceState) {
215        super.onCreate(savedInstanceState);
216        log("onCreate, inst=" + Integer.toHexString(hashCode()));
217
218        // Create a simple layout
219        LinearLayout contentView = new LinearLayout(this);
220        contentView.setOrientation(LinearLayout.VERTICAL);
221        setContentView(contentView);
222        setTitle("ConnectivityManagerTestActivity");
223
224
225        // register a connectivity receiver for CONNECTIVITY_ACTION;
226        mConnectivityReceiver = new ConnectivityReceiver();
227        registerReceiver(mConnectivityReceiver,
228                new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
229
230        mWifiReceiver = new WifiReceiver();
231        IntentFilter mIntentFilter = new IntentFilter();
232        mIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
233        mIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
234        mIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
235        mIntentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
236        mIntentFilter.addAction(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
237        mIntentFilter.addAction(ConnectivityManager.ACTION_TETHER_STATE_CHANGED);
238        registerReceiver(mWifiReceiver, mIntentFilter);
239
240        // Get an instance of ConnectivityManager
241        mCM = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
242        // Get an instance of WifiManager
243        mWifiManager =(WifiManager)getSystemService(Context.WIFI_SERVICE);
244        mChannel = mWifiManager.initialize(mContext, mContext.getMainLooper(), null);
245
246        initializeNetworkStates();
247
248        mWifiManager.setWifiEnabled(true);
249        log("Clear Wifi before we start the test.");
250        sleep(SHORT_TIMEOUT);
251        removeConfiguredNetworksAndDisableWifi();
252        mWifiRegexs = mCM.getTetherableWifiRegexs();
253     }
254
255    public List<WifiConfiguration> loadNetworkConfigurations() throws Exception {
256        InputStream in = getAssets().open(ACCESS_POINT_FILE);
257        mParseHelper = new AccessPointParserHelper(in);
258        return mParseHelper.getNetworkConfigurations();
259    }
260
261    // for each network type, initialize network states to UNKNOWN, and no verification flag is set
262    public void initializeNetworkStates() {
263        for (int networkType = NUM_NETWORK_TYPES - 1; networkType >=0; networkType--) {
264            connectivityState[networkType] =  new NetworkState();
265            log("Initialize network state for " + networkType + ": " +
266                    connectivityState[networkType].toString());
267        }
268    }
269
270    // deposit a network state
271    public void recordNetworkState(int networkType, State networkState) {
272        log("record network state for network " +  networkType +
273                ", state is " + networkState);
274        connectivityState[networkType].recordState(networkState);
275    }
276
277    // set the state transition criteria
278    public void setStateTransitionCriteria(int networkType, State initState,
279            int transitionDir, State targetState) {
280        connectivityState[networkType].setStateTransitionCriteria(
281                initState, transitionDir, targetState);
282    }
283
284    // Validate the states recorded
285    public boolean validateNetworkStates(int networkType) {
286        log("validate network state for " + networkType + ": ");
287        return connectivityState[networkType].validateStateTransition();
288    }
289
290    // return result from network state validation
291    public String getTransitionFailureReason(int networkType) {
292        log("get network state transition failure reason for " + networkType + ": " +
293                connectivityState[networkType].toString());
294        return connectivityState[networkType].getReason();
295    }
296
297    private void notifyNetworkConnectivityChange() {
298        synchronized(connectivityObject) {
299            log("notify network connectivity changed");
300            connectivityObject.notifyAll();
301        }
302    }
303    private void notifyScanResult() {
304        synchronized (this) {
305            log("notify that scan results are available");
306            scanResultAvailable = true;
307            this.notify();
308        }
309    }
310
311    private void notifyWifiState() {
312        synchronized (wifiObject) {
313            log("notify wifi state changed");
314            wifiObject.notify();
315        }
316    }
317
318    private void notifyWifiAPState() {
319        synchronized (this) {
320            log("notify wifi AP state changed");
321            this.notify();
322        }
323    }
324
325    // Update wifi tethering state
326    private void updateTetherState(Object[] available, Object[] tethered, Object[] errored) {
327        boolean wifiTethered = false;
328        boolean wifiErrored = false;
329
330        synchronized (this) {
331            for (Object obj: tethered) {
332                String str = (String)obj;
333                for (String tethRex: mWifiRegexs) {
334                    log("str: " + str +"tethRex: " + tethRex);
335                    if (str.matches(tethRex)) {
336                        wifiTethered = true;
337                    }
338                }
339            }
340
341            for (Object obj: errored) {
342                String str = (String)obj;
343                for (String tethRex: mWifiRegexs) {
344                    log("error: str: " + str +"tethRex: " + tethRex);
345                    if (str.matches(tethRex)) {
346                        wifiErrored = true;
347                    }
348                }
349            }
350
351            if (wifiTethered) {
352                mWifiTetherResult = SUCCESS;   // wifi tethering is successful
353            } else if (wifiErrored) {
354                mWifiTetherResult = FAILURE;   // wifi tethering failed
355            }
356            log("mWifiTetherResult: " + mWifiTetherResult);
357            this.notify();
358        }
359    }
360
361
362    // Wait for network connectivity state: CONNECTING, CONNECTED, SUSPENDED,
363    //                                      DISCONNECTING, DISCONNECTED, UNKNOWN
364    public boolean waitForNetworkState(int networkType, State expectedState, long timeout) {
365        long startTime = System.currentTimeMillis();
366        while (true) {
367            if ((System.currentTimeMillis() - startTime) > timeout) {
368                log("waitForNetworkState time out, the state of network type " + networkType +
369                        " is: " + mCM.getNetworkInfo(networkType).getState());
370                if (mCM.getNetworkInfo(networkType).getState() != expectedState) {
371                    return false;
372                } else {
373                    // the broadcast has been sent out. the state has been changed.
374                    log("networktype: " + networkType + " state: " +
375                            mCM.getNetworkInfo(networkType));
376                    return true;
377                }
378            }
379            log("Wait for the connectivity state for network: " + networkType +
380                    " to be " + expectedState.toString());
381            synchronized (connectivityObject) {
382                try {
383                    connectivityObject.wait(SHORT_TIMEOUT);
384                } catch (InterruptedException e) {
385                    e.printStackTrace();
386                }
387                if ((mNetworkInfo.getType() != networkType) ||
388                    (mNetworkInfo.getState() != expectedState)) {
389                    log("network state for " + mNetworkInfo.getType() +
390                            "is: " + mNetworkInfo.getState());
391                    continue;
392                }
393                return true;
394            }
395        }
396    }
397
398    // Wait for Wifi state: WIFI_STATE_DISABLED, WIFI_STATE_DISABLING, WIFI_STATE_ENABLED,
399    //                      WIFI_STATE_ENALBING, WIFI_STATE_UNKNOWN
400    public boolean waitForWifiState(int expectedState, long timeout) {
401        long startTime = System.currentTimeMillis();
402        while (true) {
403            if ((System.currentTimeMillis() - startTime) > timeout) {
404                if (mWifiState != expectedState) {
405                    return false;
406                } else {
407                    return true;
408                }
409            }
410            log("Wait for wifi state to be: " + expectedState);
411            synchronized (wifiObject) {
412                try {
413                    wifiObject.wait(SHORT_TIMEOUT);
414                } catch (InterruptedException e) {
415                    e.printStackTrace();
416                }
417                if (mWifiState != expectedState) {
418                    log("Wifi state is: " + mWifiState);
419                    continue;
420                }
421                return true;
422            }
423        }
424    }
425
426    // Wait for Wifi AP state: WIFI_AP_STATE_DISABLED, WIFI_AP_STATE_DISABLING,
427    //                         WIFI_AP_STATE_ENABLED, WIFI_STATE_ENALBING, WIFI_STATE_UNKNOWN
428    public boolean waitForWifiAPState(int expectedState, long timeout) {
429        long startTime = System.currentTimeMillis();
430        while (true) {
431            if ((System.currentTimeMillis() - startTime) > timeout) {
432                if (mWifiManager.getWifiApState() != expectedState) {
433                    return false;
434                } else {
435                    return true;
436                }
437            }
438            log("Wait for wifi AP state to be: " + expectedState);
439            synchronized (wifiObject) {
440                try {
441                    wifiObject.wait(SHORT_TIMEOUT);
442                } catch (InterruptedException e) {
443                    e.printStackTrace();
444                }
445                if (mWifiManager.getWifiApState() != expectedState) {
446                    log("Wifi state is: " + mWifiManager.getWifiApState());
447                    continue;
448                }
449                return true;
450            }
451        }
452    }
453
454    /**
455     * Wait for the wifi tethering result:
456     * @param timeout is the maximum waiting time
457     * @return SUCCESS if tethering result is successful
458     *         FAILURE if tethering result returns error.
459     */
460    public int waitForTetherStateChange(long timeout) {
461        long startTime = System.currentTimeMillis();
462        while (true) {
463            if ((System.currentTimeMillis() - startTime) > timeout) {
464                return mWifiTetherResult;
465            }
466            log("Wait for wifi tethering result.");
467            synchronized (this) {
468                try {
469                    this.wait(SHORT_TIMEOUT);
470                } catch (InterruptedException e) {
471                    e.printStackTrace();
472                }
473                if (mWifiTetherResult == INIT ) {
474                    continue;
475                } else {
476                    return mWifiTetherResult;
477                }
478            }
479        }
480    }
481
482    // Return true if device is currently connected to mobile network
483    public boolean isConnectedToMobile() {
484        return (mNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE);
485    }
486
487    // Return true if device is currently connected to Wifi
488    public boolean isConnectedToWifi() {
489        return (mNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI);
490    }
491
492    public boolean enableWifi() {
493        return mWifiManager.setWifiEnabled(true);
494    }
495
496    // Turn screen off
497    public void turnScreenOff() {
498        log("Turn screen off");
499        PowerManager pm =
500            (PowerManager) getSystemService(Context.POWER_SERVICE);
501        pm.goToSleep(SystemClock.uptimeMillis() + 100);
502    }
503
504    // Turn screen on
505    public void turnScreenOn() {
506        log("Turn screen on");
507        IPowerManager mPowerManagerService = IPowerManager.Stub.asInterface(
508                ServiceManager.getService("power"));;
509        try {
510            mPowerManagerService.userActivityWithForce(SystemClock.uptimeMillis(), false, true);
511        } catch (Exception e) {
512            log(e.toString());
513        }
514    }
515
516    /**
517     * @param pingServerList a list of servers that can be used for ping test, can be null
518     * @return true if the ping test is successful, false otherwise.
519     */
520    public boolean pingTest(String[] pingServerList) {
521        boolean result = false;
522        String[] hostList = {"www.google.com", "www.yahoo.com",
523                "www.bing.com", "www.facebook.com", "www.ask.com"};
524        if (pingServerList != null) {
525            hostList = pingServerList;
526        }
527        try {
528            // assume the chance that all servers are down is very small
529            for (int i = 0; i < hostList.length; i++ ) {
530                String host = hostList[i];
531                log("Start ping test, ping " + host);
532                Process p = Runtime.getRuntime().exec("ping -c 10 -w 100 " + host);
533                int status = p.waitFor();
534                if (status == 0) {
535                    // if any of the ping test is successful, return true
536                    result = true;
537                    break;
538                } else {
539                    result = false;
540                    log("ping " + host + " failed.");
541                }
542            }
543        } catch (UnknownHostException e) {
544            log("Ping test Fail: Unknown Host");
545        } catch (IOException e) {
546            log("Ping test Fail:  IOException");
547        } catch (InterruptedException e) {
548            log("Ping test Fail: InterruptedException");
549        }
550        log("return");
551        return result;
552    }
553
554    /**
555     * Associate the device to given SSID
556     * If the device is already associated with a WiFi, disconnect and forget it,
557     * We don't verify whether the connection is successful or not, leave this to the test
558     */
559    public boolean connectToWifi(String knownSSID) {
560        WifiConfiguration config = new WifiConfiguration();
561        config.SSID = knownSSID;
562        config.allowedKeyManagement.set(KeyMgmt.NONE);
563        return connectToWifiWithConfiguration(config);
564    }
565
566    /**
567     * Connect to Wi-Fi with the given configuration. Note the SSID in the configuration
568     * is pure string, we need to convert it to quoted string.
569     * @param config
570     * @return
571     */
572    public boolean connectToWifiWithConfiguration(WifiConfiguration config) {
573        String ssid = config.SSID;
574        config.SSID = convertToQuotedString(ssid);
575
576        //If Wifi is not enabled, enable it
577        if (!mWifiManager.isWifiEnabled()) {
578            log("Wifi is not enabled, enable it");
579            mWifiManager.setWifiEnabled(true);
580            // wait for the wifi state change before start scanning.
581            if (!waitForWifiState(WifiManager.WIFI_STATE_ENABLED, 2*SHORT_TIMEOUT)) {
582                log("wait for WIFI_STATE_ENABLED failed");
583                return false;
584            }
585        }
586
587        boolean foundApInScanResults = false;
588        for (int retry = 0; retry < 5; retry++) {
589            List<ScanResult> netList = mWifiManager.getScanResults();
590            if (netList != null) {
591                log("size of scan result list: " + netList.size());
592                for (int i = 0; i < netList.size(); i++) {
593                    ScanResult sr= netList.get(i);
594                    if (sr.SSID.equals(ssid)) {
595                        log("found " + ssid + " in the scan result list");
596                        log("retry: " + retry);
597                        foundApInScanResults = true;
598                        mWifiManager.connect(mChannel, config,
599                                new WifiManager.ActionListener() {
600                                    public void onSuccess() {
601                                    }
602                                    public void onFailure(int reason) {
603                                        log("connect failure " + reason);
604                                    }
605                                });
606                        break;
607                   }
608                }
609            }
610            if (foundApInScanResults) {
611                return true;
612            } else {
613                // Start an active scan
614                mWifiManager.startScanActive();
615                mScanResultIsAvailable = false;
616                long startTime = System.currentTimeMillis();
617                while (!mScanResultIsAvailable) {
618                    if ((System.currentTimeMillis() - startTime) > WIFI_SCAN_TIMEOUT) {
619                        log("wait for scan results timeout");
620                        return false;
621                    }
622                    // wait for the scan results to be available
623                    synchronized (this) {
624                        // wait for the scan result to be available
625                        try {
626                            this.wait(WAIT_FOR_SCAN_RESULT);
627                        } catch (InterruptedException e) {
628                            e.printStackTrace();
629                        }
630                        if ((mWifiManager.getScanResults() == null) ||
631                                (mWifiManager.getScanResults().size() <= 0)) {
632                            continue;
633                        }
634                        mScanResultIsAvailable = true;
635                    }
636                }
637            }
638        }
639        return false;
640    }
641
642    /*
643     * Disconnect from the current AP and remove configured networks.
644     */
645    public boolean disconnectAP() {
646        // remove saved networks
647        List<WifiConfiguration> wifiConfigList = mWifiManager.getConfiguredNetworks();
648        log("size of wifiConfigList: " + wifiConfigList.size());
649        for (WifiConfiguration wifiConfig: wifiConfigList) {
650            log("remove wifi configuration: " + wifiConfig.networkId);
651            int netId = wifiConfig.networkId;
652            mWifiManager.forget(mChannel, netId, new WifiManager.ActionListener() {
653                    public void onSuccess() {
654                    }
655                    public void onFailure(int reason) {
656                        log("Failed to forget " + reason);
657                    }
658                });
659        }
660        return true;
661    }
662    /**
663     * Disable Wifi
664     * @return true if Wifi is disabled successfully
665     */
666    public boolean disableWifi() {
667        return mWifiManager.setWifiEnabled(false);
668    }
669
670    /**
671     * Remove configured networks and disable wifi
672     */
673    public boolean removeConfiguredNetworksAndDisableWifi() {
674        if (!disconnectAP()) {
675           return false;
676        }
677        sleep(SHORT_TIMEOUT);
678        if (!mWifiManager.setWifiEnabled(false)) {
679            return false;
680        }
681        sleep(SHORT_TIMEOUT);
682        return true;
683    }
684
685    private void sleep(long sleeptime) {
686        try {
687            Thread.sleep(sleeptime);
688        } catch (InterruptedException e) {}
689    }
690
691    /**
692     * Set airplane mode
693     */
694    public void setAirplaneMode(Context context, boolean enableAM) {
695        //set the airplane mode
696        Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON,
697                enableAM ? 1 : 0);
698        // Post the intent
699        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
700        intent.putExtra("state", enableAM);
701        context.sendBroadcast(intent);
702    }
703
704    protected static String convertToQuotedString(String string) {
705        return "\"" + string + "\"";
706    }
707
708    @Override
709    protected void onDestroy() {
710        super.onDestroy();
711
712        //Unregister receiver
713        if (mConnectivityReceiver != null) {
714            unregisterReceiver(mConnectivityReceiver);
715        }
716        if (mWifiReceiver != null) {
717            unregisterReceiver(mWifiReceiver);
718        }
719        log("onDestroy, inst=" + Integer.toHexString(hashCode()));
720    }
721
722    @Override
723    public void onStart() {
724        super.onStart();
725        mContext = this;
726        Bundle bundle = this.getIntent().getExtras();
727        if (bundle != null){
728            mPowerSsid = bundle.getString("power_ssid");
729        }
730    }
731    //A thread to set the device into airplane mode then turn on wifi.
732    Thread setDeviceWifiAndAirplaneThread = new Thread(new Runnable() {
733        public void run() {
734            setAirplaneMode(mContext, true);
735            connectToWifi(mPowerSsid);
736        }
737    });
738
739    //A thread to set the device into wifi
740    Thread setDeviceInWifiOnlyThread = new Thread(new Runnable() {
741        public void run() {
742            connectToWifi(mPowerSsid);
743        }
744    });
745
746    @Override
747    public boolean onKeyDown(int keyCode, KeyEvent event) {
748        switch (keyCode) {
749            //This is a tricky way for the scripted monkey to
750            //set the device in wifi and wifi in airplane mode.
751            case KeyEvent.KEYCODE_1:
752                setDeviceWifiAndAirplaneThread.start();
753                break;
754
755            case KeyEvent.KEYCODE_2:
756                setDeviceInWifiOnlyThread.start();
757                break;
758        }
759        return super.onKeyDown(keyCode, event);
760    }
761
762    private void log(String message) {
763        Log.v(LOG_TAG, message);
764    }
765}
766