[android开发篇][ wifi模块] [2] wifibase

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[android开发篇][ wifi模块] [2] wifibase相关的知识,希望对你有一定的参考价值。

package com.softwinner.network.wifi;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.RemoteException;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.UiCollection;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiScrollable;
import android.support.test.uiautomator.UiSelector;
import android.support.test.uiautomator.Until;
import android.util.Log;


import com.softwinner.settings.WIFI;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.junit.Assert.assertTrue;

/**
 * @author liuzhipeng
 * Created by Administrator on 2017/6/27.
 */

public class wifiBaseClass {
//    private String packageName = "com.example.black.wifiswitch";
    private UiDevice mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    private String ssid ;
    private String password ;
    private String mLogTag ;
    private WifiManager mWifiManager;
//    = (WifiManager) InstrumentationRegistry.getContext().getSystemService(Context.WIFI_SERVICE);
//    private


    public wifiBaseClass(Context context, UiDevice device, String SSID, String passwd, String logTag){
        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        mDevice = device;
        ssid = SSID;
        password = passwd;
        mLogTag = logTag;
//        packageName = packName;
    }

    /**
     * add network and connect by ui operation; 最稳定的方法是调用:this.addNetworkAndConnect
     * @author liuzhipeng
     * @return
     * @throws UiObjectNotFoundException
     */

    public boolean connectwifi() throws UiObjectNotFoundException {

        mDevice.pressHome();
        triggerOffWifi();
        triggerOnWifi();
        try {mDevice.wakeUp();} catch (RemoteException e) {e.printStackTrace();}
        UiObject settingsObj = mDevice.findObject(new UiSelector().text("Settings"));
        assertTrue("find settings fail", settingsObj.waitForExists(2000));
        Log.i(mLogTag, "find settings successfully");
        settingsObj.clickAndWaitForNewWindow();
        UiObject wifiObj = mDevice.findObject(new UiSelector().resourceId("android:id/title").text("Wi?Fi"));
        assertTrue("find wifi fail", wifiObj.waitForExists(2000));
        Log.i(mLogTag, "find wifi successfully");
        wifiObj.clickAndWaitForNewWindow();
        UiObject addNetworkObj = mDevice.findObject(new UiSelector().text("Add network"));
        if(!addNetworkObj.waitForExists(1000)){
            UiScrollable scroll = new UiScrollable(new UiSelector().scrollable(true));
            if(scroll.waitForExists(25000)) {scroll.scrollToEnd(10);}
            addNetworkObj = mDevice.findObject(new UiSelector().text("Add network"));
            assertTrue("find add network fail", addNetworkObj.waitForExists(2000));
        }
        addNetworkObj.clickAndWaitForNewWindow();
        UiObject securityObj = mDevice.findObject(new UiSelector().resourceId("com.android.settings:id/security"));
        assertTrue(securityObj.waitForExists(2000));
        Log.i(mLogTag, "enter add network successfully");
        securityObj.clickAndWaitForNewWindow();
        UiObject WPAObj = mDevice.findObject(new UiSelector().text("WPA/WPA2 PSK"));
        assertTrue(WPAObj.waitForExists(2000));
        WPAObj.clickAndWaitForNewWindow();
        UiCollection collection = new UiCollection(new UiSelector().resourceId("com.android.settings:id/security"));
        UiSelector childPattern = new UiSelector().resourceId("android:id/text1").text("WPA/WPA2 PSK");
        UiObject childObj = collection.getChild(childPattern);
        assertTrue(childObj.waitForExists(2000));
        Log.i(mLogTag, "add network: set security successfully");
        UiObject networkNameObj = mDevice.findObject(new UiSelector().text("Enter the SSID"));
        assertTrue("find pollup: add network fail", networkNameObj.waitForExists(2000));
        networkNameObj.clearTextField();
        networkNameObj.setText(ssid);
        Log.i(mLogTag, "add network: input networkName successfully");
        UiObject passwordObj = mDevice.findObject(new UiSelector().resourceId("com.android.settings:id/password"));
        assertTrue(passwordObj.waitForExists(2000));
        passwordObj.clearTextField();
        passwordObj.setText(password);
        Log.i(mLogTag, "add network: input password successfully");
        UiObject saveObj = mDevice.findObject(new UiSelector().text("SAVE"));
        assertTrue(saveObj.waitForExists(2000));
        saveObj.clickAndWaitForNewWindow();
        Log.i(mLogTag, "add network: save add network");
        return true;

    }

    /**
     * trigger on wifi
     * @author liuzhipeng
     */
    public void triggerOnWifi(){

        mWifiManager.setWifiEnabled(true);
        if(mWifiManager.getWifiState() != WifiManager.WIFI_STATE_ENABLED)
        {
            try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
        }

    }

    /**
     * trigger off wifi
     * @author liuzhipeng
     */
    public void triggerOffWifi(){

        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
        while(mWifiManager.getWifiState() != WifiManager.WIFI_STATE_DISABLED){
            try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
        }
    }

    /**
     * 判断wifi 的状态; 即使断开某个wifi 连接,只要没有关掉wifi,wifi还是enabled
     * @author liuzhipeng
     * @return wifiState
     */
    public int checkWifiState(){

//        WifiManager mWifiManager = (WifiManager) InstrumentationRegistry.getContext().getSystemService(Context.WIFI_SERVICE);
        int tempInt =  mWifiManager.getWifiState();
        switch (tempInt){
            case WifiManager.WIFI_STATE_DISABLING:
                Log.i(mLogTag, "wifi state: disabling");
                break;
            case WifiManager.WIFI_STATE_DISABLED:
                Log.i(mLogTag, "wifi state: disabled");
                break;
            case WifiManager.WIFI_STATE_ENABLING:
                Log.i(mLogTag, "wifi state: enabling");
                break;
            case WifiManager.WIFI_STATE_ENABLED:
                Log.i(mLogTag, "wifi state: enabled");
                break;
            case WifiManager.WIFI_STATE_UNKNOWN:
                Log.i(mLogTag, "wifi state: unknown");
                break;
            default:
                break;
        }
        return tempInt;

    }

    /**
     * @author liuzhipeng
     * 判断wifi 是否连接成功,不是networkAvilable
     * @return true if wifi connected else false
     */
    public static boolean isWifiConnected(){

        ConnectivityManager connectivityManager = (ConnectivityManager) InstrumentationRegistry
                .getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        return (info != null && info.isConnected() && (info.getType() == ConnectivityManager.TYPE_WIFI));
    }


    /**
     * check network whether is available or not; Process调用shell 无效
     * @author liuzhipeng
     * @param command
     * @return
     */
    public boolean isNetworkAvailableByShell(String command) throws IOException {

        boolean result = false;
        List<String> resultList = new ArrayList<String>();
//        String command = "ping -c 10 -w 5 " + ip;
        try {
            Process process = Runtime.getRuntime().exec(command);
            int exitValue = process.waitFor();
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            while((line = input.readLine()) != null){
                resultList.add(line);
            }
            input.close();
            if (0 == exitValue) {
                Log.i(mLogTag,"call shell successfully,return code is :" + exitValue);
                result = true;
            }
            else{
                Log.i(mLogTag,"call shell failed. error code is :" + exitValue);
                result = false;

            }
        }
        catch (Throwable e) {
            Log.i(mLogTag,"call shell failed. " + e);
            result = false;
        }
        for (String line : resultList){
            Log.i(mLogTag,line);
        }
        return result;

    }

    /**
     * 调用device.executeShellCommand, process行不通;原因暂时不明
     * @author liuzhipeng
     * @param cmd
     * @return
     * @throws IOException
     */
    public boolean isNetworkAvailableByDevice(String cmd) throws IOException {

        boolean result = false;
        String outputOfCmd = mDevice.executeShellCommand(cmd);
        assertTrue("exec shell cmd return null", !outputOfCmd.isEmpty());
        String[] resultList = outputOfCmd.split("\n");
        for(String line : resultList){
            Log.i(mLogTag, line);
        }
        String text = resultList[resultList.length - 2];
        Log.i(mLogTag, "reverse 2 line = " + text);
        String pattern = "(\\d+).*transmitted.*\\s+(\\d+)\\s+received";
        Matcher m = Pattern.compile(pattern).matcher(text);
        if(m.find()){
            Log.i(mLogTag, "send packet num = " + m.group(1));
            Log.i(mLogTag, "receive packet num = " + m.group(2));
            assertTrue(m.group(1).equals(m.group(2)));
            return true;
        }
        return false;

    }

    /**
     *@author liuzhipeng
     * disconnect wifi, 断开wifi连接
     */
    public boolean disconnectWifi(){

        WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
        int netId = mWifiInfo.getNetworkId();
        if(-1 == netId){
            Log.i(mLogTag, "there is not currently connected network");
            return true;
        }
        mWifiManager.disableNetwork(netId);
        mWifiInfo = null;
        return mWifiManager.disconnect();
    }

    /**
     * add network and connect, 返回值为true只是说明去连接该wifi,但没有说明连接成功;可以通过
     * this.isWifiConnected来判断wifi是否连接成功
     * @param typeInt
     * @return
     */
    public boolean addNetworkAndConnect(int typeInt){
        /**
         * 必须等待wifi 为enable状态
         */
        mWifiManager.setWifiEnabled(true);
        while(mWifiManager.getWifiState() != WifiManager.WIFI_STATE_ENABLED){
            try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}
        }
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + ssid + "\"";
        WifiConfiguration tempConfig = isExsits(ssid);
        if(tempConfig != null){
            Log.i(mLogTag, ssid + " has configured, reconfigure");
            mWifiManager.removeNetwork(tempConfig.networkId);
        }
        else Log.i(mLogTag, ssid + " has not configured");
        if (typeInt == 0)// OPEN
        {
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            int res = mWifiManager.addNetwork(config);
            Log.i(mLogTag, "add open network return = " + res);
            if(res == -1){ return  false;}
            return mWifiManager.enableNetwork(res, true);
        }
        else if (typeInt == 1) //WEP
        {
            config.hiddenSSID = true;
            config.wepKeys[0] = "\"" + password + "\"";
            config.wepTxKeyIndex = 0;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);

            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            int res = mWifiManager.addNetwork(config);
            Log.i(mLogTag, "add wep network return = " + res);
            if(res == -1){ return  false;}
            return mWifiManager.enableNetwork(res, true);

        }
        else if (typeInt == 2) //PSK
        {
            config.hiddenSSID = true;
            config.preSharedKey = "\"" + password + "\"";
            config.status = WifiConfiguration.Status.ENABLED;
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
//            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);

            int res = mWifiManager.addNetwork(config);
            Log.i(mLogTag, "add WPA network return = " + res);
            if(res == -1){ return  false;}
            boolean isEnableNetwork = mWifiManager.enableNetwork(res, true);
            boolean changeHappen = mWifiManager.saveConfiguration();
            if (changeHappen) {
                Log.i(mLogTag, "config save successfully");
            } else {
                Log.i(mLogTag, "config save fail");
            }
            return isEnableNetwork;
        }

        return false;
    }

    public WifiConfiguration isExsits(String str) {
        List<WifiConfiguration> configurationList = mWifiManager.getConfiguredNetworks();
        for(WifiConfiguration configuration : configurationList){
            if(configuration.SSID.equals("\"" + str + "\""))
                return configuration;
        }
        return null;
    }


    /**
     * 获取wifi 名字
     * @author liuzhipeng
     * @return wifi 名字
     */

    public String getNetworkName(){
        WifiInfo info =  mWifiManager.getConnectionInfo();
        String wifiId = (info != null ? info.getSSID() : null);
        return wifiId.replace("\"","");
    }

    public static class Security{

        public static int OPEN = 0;
        public static int WEP = 1;
        public static int PSK = 2;
        public static int EAP = 3;
//        Security() {throw new RuntimeException("Stub!");}
    }

}

 

以上是关于[android开发篇][ wifi模块] [2] wifibase的主要内容,如果未能解决你的问题,请参考以下文章

WIFI模块开发教程之W600网络篇2:AP模式下TCP Server通信

3-STM32物联网开发WIFI(ESP8266)+GPRS(Air202)系统方案升级篇(项目功能演示--远程升级WIFI模块程序)

Android开发—智能家居系列:UDP通信发送指令

3-STM32物联网开发WIFI(ESP8266)+GPRS(Air202)系统方案基础篇(项目功能演示--GPRS )

WIFI模块开发教程之W600网络篇1:AP模式下TCP Client通信

Android开发—智能家居系列:用手机对WIFI模块进行配置