设置静态IP地址

<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<!-- wifi控制和状态权限 -->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- 网络状态改变的权限 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<!-- 6.0以上打开蓝牙和wifi最好加上定位权限,获取wifi列表要用 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- 获取IP地址 -->
<uses-permission android:name="android.permission.INTERNET"/>

 

package com.mcl.printer.utils;


import android.app.Activity;
import android.net.DhcpInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;

import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Preeth on 12/7/17
 */

public class IPSettings {

    public static final int IP_SETTING_STATE_CONNECT_SUCCESS = 1001;
    public static final int IP_SETTING_STATE_CONNECT_FAIL = 1002;
    public static final int IP_SETTING_STATE_SETSTATIC_SUCCESS = 1003;
    public static final int IP_SETTING_STATE_SETSTATIC_FAIL = 1004;
    public static final int IP_SETTING_STATE_SETSTATIC_OTHER = 1010;

    public interface IPSettringListener {
        void ipSettingState(int state);
    }

    public IPSettings(WifiManager mWifiManager) {
        this.mWifiManager = mWifiManager;
    }

    private WifiManager mWifiManager;
    private List<WifiConfiguration> mWifiConfigurations; //已经保存的wifi
    public List<ScanResult> mWifiList;//扫描出的全部wifi
    private WeakReference<IPSettringListener> ipSettringListenerWeakReference;

    public void setIpSettringListener(IPSettringListener ipSettringListener) {
        ipSettringListenerWeakReference = new WeakReference<>(ipSettringListener);
    }

    /**
     * 得到配置好的网络连接
     *
     * @return
     */
    public List<WifiConfiguration> getHaveExistWifi() {
        mWifiConfigurations = mWifiManager.getConfiguredNetworks();
        return mWifiConfigurations;
    }

    /**
     * 扫描wifi
     *
     * @return
     */
    public boolean scanWifi() {
        return mWifiManager.startScan();
    }

    /**
     * 获得当前的连接WIFI
     *
     * @return
     */
    public WifiConfiguration getConnectConfig() {
        WifiInfo connectionInfo = getConnectionInfo();
        List<WifiConfiguration> configuredNetworks = getHaveExistWifi();
        WifiConfiguration wifiConfig = null;
        if (configuredNetworks != null) {
            for (WifiConfiguration conf : configuredNetworks) {
                if (conf.networkId == connectionInfo.getNetworkId()) {
                    wifiConfig = conf;
                    break;
                }
            }
        }
        return wifiConfig;
    }

    public WifiInfo getConnectionInfo() {
        return mWifiManager.getConnectionInfo();
    }

    /**
     * 连接指定wifi
     */
    public void connectWifi(@NonNull String ssid, String pwd) {
//        IPSettings.removeWifiBySsid(mWifiManager);
        if (scanWifi()) {
            mWifiList = mWifiManager.getScanResults();
            for (ScanResult scanResult : mWifiList) {
                if (ssid.equals(scanResult.SSID)) {
                    connect(ssid, pwd, WifiCipherType.WIFICIPHER_WPA);
                    break;
                }
            }
        }
    }


    private ConnectTask connectTask;

    /**
     * 提供一个外部接口,传入要连接的无线网
     *
     * @param ssid
     * @param password
     * @param type
     */
    private void connect(String ssid, String password, IPSettings.WifiCipherType type) {
        if (connectTask == null) {
            connectTask = new ConnectTask(ssid, password, type);
            connectTask.execute();
        }
    }

    private class ConnectTask extends AsyncTask<String, Integer, Integer> {
        private String ssid;
        private String password;
        private IPSettings.WifiCipherType type;
        private int Num = 0;

        public ConnectTask(String ssid, String password, WifiCipherType type) {
            this.ssid = ssid;
            this.password = password;
            this.type = type;
        }

        @Override
        protected Integer doInBackground(String... strings) {
            try {
                openWifi(); // 打开wifi
                Thread.sleep(200);
                // 开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右),所以要等到wifi
                // 状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句
                while (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
                    try {
                        // 为了避免程序一直while循环,让它睡个100毫秒检测……
                        Thread.sleep(100);
                    } catch (InterruptedException ie) {
                    }
                }

                WifiConfiguration wifiConfig = IPSettings.createWifiInfo(ssid, password, type);
                if (wifiConfig == null) {
                    return IP_SETTING_STATE_CONNECT_FAIL;
                }

                WifiConfiguration tempConfig = IPSettings.isExsits(ssid, mWifiManager);

                if (tempConfig != null) {
                    mWifiManager.removeNetwork(tempConfig.networkId);
                }

                int netID = mWifiManager.addNetwork(wifiConfig);
                boolean enabled = mWifiManager.enableNetwork(netID, true);
                boolean connected = mWifiManager.reconnect();
                Log.i("djh", "wifi链接--enabled=" + enabled + "---connected=" + connected);
                if (enabled && connected) {
                    Thread.sleep(3000);
                    Log.i("djh", "连接WiFi成功");
                    return IP_SETTING_STATE_CONNECT_SUCCESS;
                } else {
                    if (Num < 3) {
                        Num++;
                        connect(ssid, password, type);
                    } else {
                        Log.i("djh", "连接WiFi失败");
                        return IP_SETTING_STATE_CONNECT_FAIL;
                    }
                }
            } catch (Exception e) {
                Log.e("djh", "连接WiFi失败---Exception--" + e.getMessage());
                e.printStackTrace();
            }
            return IP_SETTING_STATE_SETSTATIC_OTHER;
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            if (ipSettringListenerWeakReference != null && ipSettringListenerWeakReference.get() != null) {
                ipSettringListenerWeakReference.get().ipSettingState(integer);
            }
            connectTask = null;
        }
    }

    /**
     * 简单设置静态IP
     *
     * @param IPAdress
     * @return
     */
    public void setStaticIP(String IPAdress) {
        DhcpInfo info = mWifiManager.getDhcpInfo();
        setStaticIP(IPAdress, intToIp(info.gateway), 24, new String[]{intToIp(info.dns1), intToIp(info.dns2)});
    }


    StaticIpTask staticIpTask;

    /**
     * 设置静态IP
     *
     * @return
     */
    public void setStaticIP(String IP_ADDRESS, String GATEWAY, int PREFIX_LENGTH, String[] dns) {
        if (staticIpTask == null) {
            staticIpTask = new StaticIpTask(IP_ADDRESS, GATEWAY, PREFIX_LENGTH, dns);
            staticIpTask.execute();
        }
    }

    class StaticIpTask extends AsyncTask<String, Integer, Integer> {

        private String ip;
        private String gateway;
        private int prefix_length;
        private String[] dns;

        private boolean isRun = true;
        private int num = 0;
        private int getWifCogNum = 0;
        private boolean isWifiNum = true;

        public StaticIpTask(String ip, String gateway, int prefix_length, String[] dns) {
            this.ip = ip;
            this.gateway = gateway;
            this.prefix_length = prefix_length;
            this.dns = dns;
        }

        @Override
        protected Integer doInBackground(String... strings) {
            try {
                WifiConfiguration wifiConfiguration = null;
                while (isWifiNum) {
                    Thread.sleep(1000);
                    wifiConfiguration = getConnectConfig();
                    if (wifiConfiguration != null) {
                        break;
                    }
                    getWifCogNum++;
                    if (getWifCogNum > 5) {
                        isWifiNum = false;
                    }
                }

                InetAddress[] dns_servers = new InetAddress[0];
                dns_servers = new InetAddress[]{InetAddress.getByName(dns[0]), InetAddress.getByName(dns[1])};
                wifiConfiguration = IPSettings.setStaticIpConfiguration(wifiConfiguration, InetAddress.getByName(this.ip), this.prefix_length, InetAddress.getByName(this.gateway), dns_servers);
                int updateNetwork = mWifiManager.updateNetwork(wifiConfiguration);
                boolean saveConfiguration = mWifiManager.saveConfiguration();

                int netId = mWifiManager.addNetwork(wifiConfiguration);
                mWifiManager.disableNetwork(netId);
                boolean flag = mWifiManager.enableNetwork(netId, true);

                while (isRun) {

                    Thread.sleep(1000);

                    if (IPSettings.getIpStr(mWifiManager).equals(this.ip)) {
                        isRun = false;
                        Log.e("djh", "设置静态IP成功" + IPSettings.getIpStr(mWifiManager));
                        return IPSettings.IP_SETTING_STATE_SETSTATIC_SUCCESS;
                    }
                    num++;
                    if (num > 8) {
                        isRun = false;
                        Log.e("djh", "设置静态IP失败" + IPSettings.getIpStr(mWifiManager));
                        return IPSettings.IP_SETTING_STATE_SETSTATIC_FAIL;
                    }
                }
            } catch (UnknownHostException | InterruptedException e) {
                e.printStackTrace();
            }
            return IPSettings.IP_SETTING_STATE_SETSTATIC_OTHER;
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            if (ipSettringListenerWeakReference != null && ipSettringListenerWeakReference.get() != null) {
                ipSettringListenerWeakReference.get().ipSettingState(integer);
            }
            staticIpTask = null;
        }
    }

    /**
     * 打开wifi功能
     *
     * @return
     */
    private boolean openWifi() {
        boolean bRet = true;
        if (!mWifiManager.isWifiEnabled()) {
            bRet = mWifiManager.setWifiEnabled(true);
        }
        return bRet;
    }

    /**
     * 获得wifi设置是否静态
     *
     * @return
     */
    public String getWifiSetting() {
        DhcpInfo dhcpInfo = mWifiManager.getDhcpInfo();
        if (dhcpInfo.leaseDuration == 0) {
            return "StaticIP";
        } else {
            return "DHCP";
        }
    }

    /**
     * 获取IP地址
     *
     * @return
     */
    public static String getIpStr(WifiManager wifiManager) {
        WifiInfo w = wifiManager.getConnectionInfo();
        return intToIp(w.getIpAddress());
    }


    //WIFICIPHER_WEP是WEP ,WIFICIPHER_WPA是WPA,WIFICIPHER_NOPASS没有密码
    public enum WifiCipherType {
        WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
    }

    @SuppressWarnings("unchecked")
    public static WifiConfiguration setStaticIpConfiguration(WifiConfiguration conf, InetAddress ipAddress, int prefixLength, InetAddress gateway, InetAddress[] dns) {
        try {
            // Set up IpAssignment to STATIC.
            Object ipAssignment = getEnumValue("android.net.IpConfiguration$IpAssignment", "STATIC");
            callMethod(conf, "setIpAssignment", new String[]{"android.net.IpConfiguration$IpAssignment"}, new Object[]{ipAssignment});

            // Set properties in StaticIpConfiguration.
            Object staticIpConfig = newInstance("android.net.StaticIpConfiguration");
            Object linkAddress = newInstance("android.net.LinkAddress", new Class<?>[]{InetAddress.class, int.class}, new Object[]{ipAddress, prefixLength});

            setField(staticIpConfig, "ipAddress", linkAddress);
            setField(staticIpConfig, "gateway", gateway);
            getField(staticIpConfig, "dnsServers", ArrayList.class).clear();
            for (InetAddress dn : dns)
                getField(staticIpConfig, "dnsServers", ArrayList.class).add(dn);

            callMethod(conf, "setStaticIpConfiguration", new String[]{"android.net.StaticIpConfiguration"}, new Object[]{staticIpConfig});
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conf;
    }

    private static Object newInstance(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
        return newInstance(className, new Class<?>[0], new Object[0]);
    }

    private static Object newInstance(String className, Class<?>[] parameterClasses, Object[] parameterValues) throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException {
        Class<?> clz = Class.forName(className);
        Constructor<?> constructor = clz.getConstructor(parameterClasses);
        return constructor.newInstance(parameterValues);
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    private static Object getEnumValue(String enumClassName, String enumValue) throws ClassNotFoundException {
        Class<Enum> enumClz = (Class<Enum>) Class.forName(enumClassName);
        return Enum.valueOf(enumClz, enumValue);
    }

    private static void setField(Object object, String fieldName, Object value) throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException {
        Field field = object.getClass().getDeclaredField(fieldName);
        field.set(object, value);
    }

    private static <T> T getField(Object object, String fieldName, Class<T> type) throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException {
        Field field = object.getClass().getDeclaredField(fieldName);
        return type.cast(field.get(object));
    }

    private static void callMethod(Object object, String methodName, String[] parameterTypes, Object[] parameterValues) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
        Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
        for (int i = 0; i < parameterTypes.length; i++)
            parameterClasses[i] = Class.forName(parameterTypes[i]);

        Method method = object.getClass().getDeclaredMethod(methodName, parameterClasses);
        method.invoke(object, parameterValues);
    }


    /************************************获得ip信息*********************************************/
    public static String intToIp(int addr) {
        return ((addr & 0xFF) + "." +
                ((addr >>>= 8) & 0xFF) + "." +
                ((addr >>>= 8) & 0xFF) + "." +
                ((addr >>>= 8) & 0xFF));
    }

    public static Map<String, String> getWifiNetInfo(WifiManager wifiManager) {
        Map<String, String> wifiInfo = new HashMap<>();
        WifiManager wifi = wifiManager;
        if (wifi != null) {
            DhcpInfo info = wifi.getDhcpInfo();
            wifiInfo.put("wifi-dns", intToIp(info.dns1) + ";" + intToIp(info.dns2));
            wifiInfo.put("wifi-gateway", intToIp(info.gateway));
            wifiInfo.put("wifi-ip", intToIp(info.ipAddress));
            wifiInfo.put("wifi-netmask", intToIp(info.netmask));
            wifiInfo.put("wifi-leaseTime", String.valueOf(info.leaseDuration));
            wifiInfo.put("wifi-dhcpServer", intToIp(info.serverAddress));
        }
        return wifiInfo;
    }


    /**
     * 忘记某一个wifi密码
     *
     * @param wifiManager
     */
    public static void removeWifiBySsid(WifiManager wifiManager) {
        List<WifiConfiguration> wifiConfigs = wifiManager.getConfiguredNetworks();
        if (wifiConfigs != null) {
            for (WifiConfiguration wifiConfig : wifiConfigs) {
                if (wifiConfig != null) {
                    wifiManager.disableNetwork(wifiConfig.networkId);
                    wifiManager.disconnect();
                    wifiManager.removeNetwork(wifiConfig.networkId);
                    wifiManager.saveConfiguration();
                }
            }
        }
    }

    /**
     * 创建wifi信息
     *
     * @param SSID
     * @param Password
     * @param Type
     * @return
     */
    public static WifiConfiguration createWifiInfo(String SSID, String Password, IPSettings.WifiCipherType Type) {

        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";
        // nopass
        if (Type == WifiCipherType.WIFICIPHER_NOPASS) {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }
        // wep
        if (Type == WifiCipherType.WIFICIPHER_WEP) {
            if (!TextUtils.isEmpty(Password)) {
                if (isHexWepKey(Password)) {
                    config.wepKeys[0] = Password;
                } else {
                    config.wepKeys[0] = "\"" + Password + "\"";
                }
            }
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        // wpa
        if (Type == WifiCipherType.WIFICIPHER_WPA) {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.TKIP);
            // 此处需要修改否则不能自动重联
            // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        return config;
    }


    private static boolean isHexWepKey(String wepKey) {
        final int len = wepKey.length();

        // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?)
        if (len != 10 && len != 26 && len != 58) {
            return false;
        }

        return isHex(wepKey);
    }

    private static boolean isHex(String key) {
        for (int i = key.length() - 1; i >= 0; i--) {
            final char c = key.charAt(i);
            if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a'
                    && c <= 'f')) {
                return false;
            }
        }

        return true;
    }

    // 查看以前是否也配置过这个网络
    public static WifiConfiguration isExsits(String SSID, WifiManager mWifiManager) {
        List<WifiConfiguration> existingConfigs = mWifiManager
                .getConfiguredNetworks();
        if (existingConfigs != null) {
            for (WifiConfiguration existingConfig : existingConfigs) {
                if (existingConfig.SSID == null) {
                    continue;
                }
                if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
                    return existingConfig;
                }
            }
        }
        return null;
    }


}

转载于:https://my.oschina.net/u/1177694/blog/3050237

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值