Android 5.0, 6.0, 7.0 코드에 대해 WIFI 연결을 정적 IP 또는 DHCP로 설정하는 방법 및 고려 사항

122839 단어
참고: Android6.0 이상 앱은 삭제, WiFi 수정 권한이 없습니다.
만약에 자신의 앱이 코드를 통해 연결된다면 (만약 시스템이 원래 이 와이파이를 기억했다면 앱에서 코드를 통해 한 번 더 연결하는 것은 제외) 권한이 필요하다.
4
android:name="android.permission.OVERRIDE_WIFI_CONFIG" />
WiFi를 삭제하고 수정할 수 있습니다.
안드로이드 6.0 이상, 다음 방법으로 -1과false를 되돌려주면 권한이 없거나 이 와이파이 창설자가 본 앱이 아니라는 것을 의미한다(각 와이파이는 다음 와이파이 창설자의 앱 id를 기록한다).
 
  
mwifiManager.updateNetwork(config);
mwifiManager.removeNetwork(tempConfig.networkId);

안드로이드 6.0 코드가 WIFI 연결 방식을 정적 IP로 설정하면 사용자에게 WiFi 설정에서 이 WiFi를 저장(또는 잊어버리거나 삭제)하지 말라고 알려야 한다. 그리고 사용자는 앱에서 WIFI를 선택하고 비밀번호를 입력하고 코드를 WiFi에 연결한 다음에 반사 호출 시스템 숨김 방법을 통해 연결 방식을 변경해야 한다.
주의: 와이파이가 정적 IP에서 DHCP로 바뀌거나 DHCP에서 정적 IP로 바뀌면 와이파이를 다시 시작해야 한다.
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disableNetwork(netId);
wifiManager.enableNetwork(netId, true);

다음은 WiFi 연결 방식을 설정하는 방법 클래스입니다.
5.0 시스템에서 직접 호출하면 수정할 수 있습니다.(5.1 디바이스 테스트 사용 가능)
6.0 이상에서false를 반환하면 해당 WIFI가 해당 APP에 의해 만들어지지 않고 수정 권한이 없어야 합니다.(APP에 연결된 WIFI 테스트 방법 사용 가능)
5.0 이하의 휴대전화가 없기 때문에 5.0 시스템 이하를 테스트하는 방법이 없다.
package com.jisai.wifiip;

import android.content.ContentResolver;
import android.content.Context;
import android.net.LinkAddress;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.hotspot2.PasspointConfiguration;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/12/4 0004.
 */

public class StaticIpUtil {
    Context mContext;

    public StaticIpUtil(Context context) {
        mContext = context;
    }

//    public void getNetworkInformation() {
//        WifiManager mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
//        int ipAddress = mWifiManager.getConnectionInfo().getIpAddress();
//        Constant.IP = intToIp(ipAddress);
//        long getwayIpS = mWifiManager.getDhcpInfo().gateway;
//        Constant.gateway = long2ip(getwayIpS);
//        //     \\,     ,yeah
//        String[] IPS = Constant.IP.split("\\.");
//        Constant.IP = IPS[0] + "." + IPS[1] + "." + IPS[2] + "." + Constant.IPLast;
//        Constant.isConnectSocket = IPS[0] + "." + IPS[1] + "." + IPS[2] + "." + Constant.IPLast;
//        String zeroIP = "0" + "." + "0" + "." + "0" + "." + Constant.IPLast;
//        String equalIP = IPS[0] + "." + IPS[1] + "." + IPS[2] + "." + IPS[3];
//        if (!Constant.IP.equals(zeroIP) && !Constant.IP.equals(equalIP)) {
//            setIpWithTfiStaticIp(false, Constant.IP, Constant.prefix, Constant.dns1, Constant.gateway);
//        }
//    }

    /**
     *    。
     *
     * @param ip
     * @return
     */
    public String long2ip(long ip) {
        StringBuffer sb = new StringBuffer();
        sb.append(String.valueOf((int) (ip & 0xff)));
        sb.append('.');
        sb.append(String.valueOf((int) ((ip >> 8) & 0xff)));
        sb.append('.');
        sb.append(String.valueOf((int) ((ip >> 16) & 0xff)));
        sb.append('.');
        sb.append(String.valueOf((int) ((ip >> 24) & 0xff)));
        return sb.toString();
    }

    public String intToIp(int ipAddress) {
        return ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "."
                + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));

    }


    /**
     *     ip     
     */

    public boolean setIpWithTfiStaticIp(boolean dhcp, String ip, int prefix, String dns1, String gateway) {
        WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        boolean flag=false;
        if (!wifiManager.isWifiEnabled()) {
            // wifi is disabled
            return flag;
        }
        // get the current wifi configuration
        WifiConfiguration wifiConfig = null;

        WifiInfo connectionInfo = wifiManager.getConnectionInfo();
        List configuredNetworks = wifiManager.getConfiguredNetworks();
        if (configuredNetworks != null) {
            for (WifiConfiguration conf : configuredNetworks) {
                if (conf.networkId == connectionInfo.getNetworkId()) {
                    wifiConfig = conf;
                    break;
                }
            }
        }

        if (wifiConfig == null) {
            // wifi is not connected
            return flag;
        }
        if (Build.VERSION.SDK_INT < 11) { //    android2.x    
            ContentResolver ctRes = mContext.getContentResolver();
            Settings.System.putInt(ctRes,
                    Settings.System.WIFI_USE_STATIC_IP, 1);
            Settings.System.putString(ctRes,
                    Settings.System.WIFI_STATIC_IP, "192.168.0.202");
            flag=true;
            return flag;
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { //    android3.x       

            try {
                setIpAssignment("STATIC", wifiConfig);
                setIpAddress(InetAddress.getByName(ip), prefix, wifiConfig);
                setGateway(InetAddress.getByName(gateway), wifiConfig);
                setDNS(InetAddress.getByName(dns1), wifiConfig);
                int netId = wifiManager.updateNetwork(wifiConfig);
                boolean result =  netId!= -1; //apply the setting
                if(result){
                    boolean isDisconnected =  wifiManager.disconnect();
                    boolean configSaved = wifiManager.saveConfiguration(); //Save it
                    boolean isEnabled = wifiManager.enableNetwork(wifiConfig.networkId, true);
                    // reconnect with the new static IP
                    boolean isReconnected = wifiManager.reconnect();
                }
             /*   wifiManager.updateNetwork(wifiConfig); // apply the setting
                wifiManager.saveConfiguration(); //Save it*/
                System.out.println("  ip    !");
                flag=true;
                return flag;
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("  ip    !");
                flag=false;
                return flag;
            }
        } else{//   android5.x       
            try {
                Class> ipAssignment = wifiConfig.getClass().getMethod("getIpAssignment").invoke(wifiConfig).getClass();
                Object staticConf = wifiConfig.getClass().getMethod("getStaticIpConfiguration").invoke(wifiConfig);

                Log.e("wifiConfig.getClass()",wifiConfig.getClass().toString());

                if (dhcp) {
                    wifiConfig.getClass().getMethod("setIpAssignment", ipAssignment).invoke(wifiConfig, Enum.valueOf((Class) ipAssignment, "DHCP"));
                    if (staticConf != null) {
                        staticConf.getClass().getMethod("clear").invoke(staticConf);
                        Log.e("      ","staticConf!=null");
                    }else{
                        Log.e("      ","staticConf==null");
                    }
                } else {
                    wifiConfig.getClass().getMethod("setIpAssignment", ipAssignment).invoke(wifiConfig, Enum.valueOf((Class) ipAssignment, "STATIC"));
                    if (staticConf == null) {
                        Log.e("  IP  ","staticConf==null");
                        Class> staticConfigClass = Class.forName("android.net.StaticIpConfiguration");
                        staticConf = staticConfigClass.newInstance();
                        if (staticConf == null) {
                            Log.e("  IP  ","staticConf  ==null");
                        }


                    }else{
                        Log.e("  IP  ","staticConf!=null");

                    }
                    // STATIC IP AND MASK PREFIX
                    Constructor> laConstructor = LinkAddress.class.getConstructor(InetAddress.class, int.class);
                    LinkAddress linkAddress = (LinkAddress) laConstructor.newInstance(
                            InetAddress.getByName(ip),
                            prefix);
                    staticConf.getClass().getField("ipAddress").set(staticConf, linkAddress);
                    // GATEWAY
                    staticConf.getClass().getField("gateway").set(staticConf, InetAddress.getByName(gateway));
                    // DNS
                    List dnsServers = (List) staticConf.getClass().getField("dnsServers").get(staticConf);
                    dnsServers.clear();
                    dnsServers.add(InetAddress.getByName(dns1));
//                    dnsServers.add(InetAddress.getByName(Constant.dns2)); // Google DNS as DNS2 for safety
                    // apply the new static configuration
                    wifiConfig.getClass().getMethod("setStaticIpConfiguration", staticConf.getClass()).invoke(wifiConfig, staticConf);
                }
                // apply the configuration change
                boolean result = wifiManager.updateNetwork(wifiConfig) != -1; //apply the setting
                Log.e("result",result+"");

                if (result) result = wifiManager.saveConfiguration(); //Save it

                Log.e("saveConfiguration",result+"");

                if (result) wifiManager.reassociate(); // reconnect with the new static IP

                Log.e("reassociate",result+"");


                int netId = wifiManager.addNetwork(wifiConfig);
                wifiManager.disableNetwork(netId);
                flag  = wifiManager.enableNetwork(netId, true);
                Log.e("netId",netId+"");


//                                            if(b){
//                                                Toast.makeText(getApplication(),"    !",Toast.LENGTH_SHORT).show();
//                                            }else{
//                                                Toast.makeText(getApplication(),"    !            !",Toast.LENGTH_SHORT).show();
//
//                                            }
//                flag=true;


            } catch (Exception e) {
                e.printStackTrace();
                flag=false;
            }

        }
        return flag;
    }




    private static void setIpAssignment(String assign, WifiConfiguration wifiConf)
            throws SecurityException, IllegalArgumentException,
            NoSuchFieldException, IllegalAccessException {
        setEnumField(wifiConf, assign, "ipAssignment");
    }


    private static void setIpAddress(InetAddress addr, int prefixLength,
                                     WifiConfiguration wifiConf) throws SecurityException,
            IllegalArgumentException, NoSuchFieldException,
            IllegalAccessException, NoSuchMethodException,
            ClassNotFoundException, InstantiationException,
            InvocationTargetException {
        Object linkProperties = getField(wifiConf, "linkProperties");
        if (linkProperties == null)
            return;
        Class> laClass = Class.forName("android.net.LinkAddress");
        Constructor> laConstructor = laClass.getConstructor(new Class[]{

                InetAddress.class, int.class});
        Object linkAddress = laConstructor.newInstance(addr, prefixLength);
        ArrayList mLinkAddresses = (ArrayList) getDeclaredField(
                linkProperties, "mLinkAddresses");
        mLinkAddresses.clear();
        mLinkAddresses.add(linkAddress);
    }

    private static Object getField(Object obj, String name)
            throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        Field f = obj.getClass().getField(name);
        Object out = f.get(obj);
        return out;
    }

    private static Object getDeclaredField(Object obj, String name)
            throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        Field f = obj.getClass().getDeclaredField(name);
        f.setAccessible(true);
        Object out = f.get(obj);
        return out;
    }


    private static void setEnumField(Object obj, String value, String name)
            throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        Field f = obj.getClass().getField(name);
        f.set(obj, Enum.valueOf((Class) f.getType(), value));
    }


    private static void setGateway(InetAddress gateway, WifiConfiguration wifiConf)
            throws SecurityException,
            IllegalArgumentException, NoSuchFieldException,
            IllegalAccessException, ClassNotFoundException,
            NoSuchMethodException, InstantiationException,
            InvocationTargetException {
        Object linkProperties = getField(wifiConf, "linkProperties");
        if (linkProperties == null)
            return;
        if (android.os.Build.VERSION.SDK_INT >= 14) { // android4.x  
            Class> routeInfoClass = Class.forName("android.net.RouteInfo");
            Constructor> routeInfoConstructor = routeInfoClass
                    .getConstructor(new Class[]{InetAddress.class});
            Object routeInfo = routeInfoConstructor.newInstance(gateway);
            ArrayList mRoutes = (ArrayList) getDeclaredField(

                    linkProperties, "mRoutes");
            mRoutes.clear();
            mRoutes.add(routeInfo);
        } else { // android3.x  
            ArrayList mGateways = (ArrayList) getDeclaredField(

                    linkProperties, "mGateways");
            //    mGateways.clear();
            mGateways.add(gateway);

        }
    }


    private static void setDNS(InetAddress dns, WifiConfiguration wifiConf)

            throws SecurityException, IllegalArgumentException,

            NoSuchFieldException, IllegalAccessException {

        Object linkProperties = getField(wifiConf, "linkProperties");
        if (linkProperties == null)
            return;
        ArrayList mDnses = (ArrayList)

                getDeclaredField(linkProperties, "mDnses");
        mDnses.clear(); //     DNS  (      ,    ,     )
        mDnses.add(dns);
        //    DNS
    }
}

호출 방법
case R.id.aaa:

    //IP       24 DNS1  1   
  Boolean b= s.setIpWithTfiStaticIp(false,"192.168.1.123",24,"255.255.255.0","192.168.1.1");
    Toast.makeText(MainActivity.this,""+b,Toast.LENGTH_SHORT).show();
    break;
case R.id.aaa2:
    //IP       24 DNS1  1   
    Boolean c=  s.setIpWithTfiStaticIp(true,"192.168.1.123",24,"255.255.255.0","192.168.1.1");
    Toast.makeText(MainActivity.this,""+c,Toast.LENGTH_SHORT).show();

    break;

코드 연결 WiFi 방법:
String ssid =  "wifisocket";
String password = "00000000";
mWifiConfiguration = CreateWifiInfo(ssid, password, 3);
System.out.println("mWifiConfiguration"+mWifiConfiguration);
int wcgID = mwifiManager.addNetwork(mWifiConfiguration);
boolean bbb = mwifiManager.enableNetwork(wcgID, true);
Log.e("wcgID",""+wcgID);
Log.e("b",""+bbb);
public WifiConfiguration CreateWifiInfo(String SSID, String Password,
                                        int Type) {
    WifiConfiguration config = new WifiConfiguration();
    config.allowedAuthAlgorithms.clear();
    config.allowedGroupCiphers.clear();
    config.allowedKeyManagement.clear();
    config.allowedPairwiseCiphers.clear();
    config.allowedProtocols.clear();
    config.SSID = "\"" + SSID+"\"";

    WifiConfiguration tempConfig = this.IsExsits(SSID);
    if (tempConfig != null) {

    Boolean c=    mwifiManager.removeNetwork(tempConfig.networkId);
        Log.e("    ",""+c);
    }

    if (Type == 1) // WIFICIPHER_NOPASS
    {
        config.wepKeys[0] = "";
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        config.wepTxKeyIndex = 0;
    }
    if (Type == 2) // WIFICIPHER_WEP
    {
        config.hiddenSSID = true;
        config.wepKeys[0] = "\"" + Password + "\"";
        config.allowedAuthAlgorithms
                .set(WifiConfiguration.AuthAlgorithm.SHARED);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        config.allowedGroupCiphers
                .set(WifiConfiguration.GroupCipher.WEP104);
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        config.wepTxKeyIndex = 0;
    }
    if (Type == 3) // 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;
}

6.0 이상 IP 설정 방법(5.0도 가능할 것 같고 위의 방법과 동일하며 위의 방법=5.X의 6.0도 가능)
키를 눌러 메서드를 호출하려면 다음과 같이 하십시오.
case R.id.aaa6:
    try {
        setStaticIpConfiguration(mwifiManager, mWifiConfiguration,
                InetAddress.getByName("106.168.0.235"), 24,
                InetAddress.getByName("192.168.0.202"),
                InetAddress.getAllByName("8.8.8.8"));
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    break;
@SuppressWarnings("unchecked")
public static void setStaticIpConfiguration(WifiManager manager,
                                            WifiConfiguration config, InetAddress ipAddress, int prefixLength,
                                            InetAddress gateway, InetAddress[] dns)
        throws ClassNotFoundException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException,
        NoSuchMethodException, NoSuchFieldException, InstantiationException {
    // First set up IpAssignment to STATIC.
    Object ipAssignment = getEnumValue(
            "android.net.IpConfiguration$IpAssignment", "STATIC");
    callMethod(config, "setIpAssignment",
            new String[] { "android.net.IpConfiguration$IpAssignment" },
            new Object[] { ipAssignment });

    // Then 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);
    ArrayList aa = (ArrayList) getField(staticIpConfig,
            "dnsServers");
    aa.clear();
    for (int i = 0; i < dns.length; i++)
        aa.add(dns[i]);
    callMethod(config, "setStaticIpConfiguration",
            new String[] { "android.net.StaticIpConfiguration" },
            new Object[] { staticIpConfig });
    System.out.println("conconconm" + config);
    int updateNetwork = manager.updateNetwork(config);
    boolean saveConfiguration = manager.saveConfiguration();
    System.out.println("updateNetwork" + updateNetwork + saveConfiguration);

    System.out.println("ttttttttttt" + "  ");

    int netId = manager.addNetwork(config);
    manager.disableNetwork(netId);
    boolean  flag  = manager.enableNetwork(netId, true);
    Log.e("netId",netId+"");
    Log.e("flag",flag+"");

}



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



@SuppressWarnings({ "rawtypes", "unchecked" })
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 enumClz = (Class) 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 Object getField(Object object, String fieldName)
        throws IllegalAccessException, IllegalArgumentException,
        NoSuchFieldException {
    Field field = object.getClass().getDeclaredField(fieldName);
    Object out = field.get(object);
    return out;
}



@SuppressWarnings("rawtypes")
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);
}


public String intToIp(int ipAddress) {
    return ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "."
            + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));

}
//     set                   :
public static String int2ip(int ip) {
    StringBuilder sb = new StringBuilder();
    sb.append(String.valueOf((int) (ip & 0xff)));
    sb.append('.');
    sb.append(String.valueOf((int) ((ip >> 8) & 0xff)));
    sb.append('.');
    sb.append(String.valueOf((int) ((ip >> 16) & 0xff)));
    sb.append('.');
    sb.append(String.valueOf((int) ((ip >> 24) & 0xff)));
    return sb.toString();
}

IP 보기 방법:
case R.id.aaa3:
    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    WifiInfo w=wifiManager.getConnectionInfo();
    String ip=intToIp(w.getIpAddress());
    Log.e("IP",ip);
    Toast.makeText(MainActivity.this,ip,Toast.LENGTH_SHORT).show();
    break;

연결 방식을 보는 방법:
public String getWifiSetting(Context context){
    WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
    DhcpInfo dhcpInfo=wifiManager.getDhcpInfo();
     netmaskIpL=dhcpInfo.netmask;
    if(dhcpInfo.leaseDuration==0){
        return "StaticIP";
    }else{
        return "DHCP";
    }
}
package com.jisai.wifiip;

import android.content.ContentResolver;
import android.content.Context;
import android.net.DhcpInfo;
import android.net.LinkAddress;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.BoolRes;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

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.List;

public class MainActivity extends AppCompatActivity {
Button aaa,aaa2,aaa3,aaa4,aaa5,aaa6;
    long netmaskIpL;
    StaticIpUtil  s;
    WifiConfiguration mWifiConfiguration;
    private static final int SELECTED_PREMMSION_STORAGE = 6;
    private WifiManager mwifiManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        aaa= (Button) findViewById(R.id.aaa);
        aaa.setOnClickListener(ccc);

        aaa2= (Button) findViewById(R.id.aaa2);
        aaa2.setOnClickListener(ccc);

        aaa3= (Button) findViewById(R.id.aaa3);
        aaa3.setOnClickListener(ccc);

        aaa4= (Button) findViewById(R.id.aaa4);
        aaa4.setOnClickListener(ccc);

        aaa5= (Button) findViewById(R.id.aaa5);
        aaa5.setOnClickListener(ccc);

        aaa6= (Button) findViewById(R.id.aaa6);
        aaa6.setOnClickListener(ccc);

        s= new StaticIpUtil(MainActivity.this);
        mwifiManager = (WifiManager) MainActivity.this.getSystemService(WIFI_SERVICE);

    }

    View.OnClickListener ccc = new View.OnClickListener() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.aaa:

                    //IP       24 DNS1  1   
                  Boolean b= s.setIpWithTfiStaticIp(false,"192.168.1.123",24,"255.255.255.0","192.168.1.1");
                    Toast.makeText(MainActivity.this,""+b,Toast.LENGTH_SHORT).show();
                    break;
                case R.id.aaa2:
                    //IP       24 DNS1  1   
                    Boolean c=  s.setIpWithTfiStaticIp(true,"192.168.1.123",24,"255.255.255.0","192.168.1.1");
                    Toast.makeText(MainActivity.this,""+c,Toast.LENGTH_SHORT).show();

                    break;
                case R.id.aaa3:
                    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
                    WifiInfo w=wifiManager.getConnectionInfo();
                    String ip=intToIp(w.getIpAddress());
                    Log.e("IP",ip);
                    Toast.makeText(MainActivity.this,ip,Toast.LENGTH_SHORT).show();
                    break;
                case R.id.aaa4:
                    Toast.makeText(MainActivity.this,getWifiSetting(MainActivity.this),Toast.LENGTH_SHORT).show();
                    break;
                case R.id.aaa5:

                    String ssid =  "wifisocket";
                    String password = "00000000";
                    mWifiConfiguration = CreateWifiInfo(ssid, password, 3);
                    System.out.println("mWifiConfiguration"+mWifiConfiguration);
                    int wcgID = mwifiManager.addNetwork(mWifiConfiguration);
                    boolean bbb = mwifiManager.enableNetwork(wcgID, true);
                    Log.e("wcgID",""+wcgID);
                    Log.e("b",""+bbb);
                    break;

                case R.id.aaa6:
                    try {
                        setStaticIpConfiguration(mwifiManager, mWifiConfiguration,
                                InetAddress.getByName("106.168.0.235"), 24,
                                InetAddress.getByName("192.168.0.202"),
                                InetAddress.getAllByName("8.8.8.8"));
                    } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (NoSuchFieldException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (UnknownHostException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    break;

            }
        }
    };



    public String getWifiSetting(Context context){
        WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
        DhcpInfo dhcpInfo=wifiManager.getDhcpInfo();
         netmaskIpL=dhcpInfo.netmask;
        if(dhcpInfo.leaseDuration==0){
            return "StaticIP";
        }else{
            return "DHCP";
        }
    }






    public WifiConfiguration CreateWifiInfo(String SSID, String Password,
                                            int Type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID+"\"";

        WifiConfiguration tempConfig = this.IsExsits(SSID);
        if (tempConfig != null) {

        Boolean c=    mwifiManager.removeNetwork(tempConfig.networkId);
            Log.e("    ",""+c);
        }

        if (Type == 1) // WIFICIPHER_NOPASS
        {
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == 2) // WIFICIPHER_WEP
        {
            config.hiddenSSID = true;
            config.wepKeys[0] = "\"" + Password + "\"";
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == 3) // 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;
    }



    //         WiFi       SSID WifiConfiguration
    public WifiConfiguration IsExsits(String SSID) {
        List existingConfigs = mwifiManager
                .getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs) {
            System.out.println("existingConfig" + existingConfig.SSID);
            if (existingConfig.SSID.equals("\"" + SSID+"\"")) {
                return existingConfig;
            }
        }
        return null;
    }



    @SuppressWarnings("unchecked")
    public static void setStaticIpConfiguration(WifiManager manager,
                                                WifiConfiguration config, InetAddress ipAddress, int prefixLength,
                                                InetAddress gateway, InetAddress[] dns)
            throws ClassNotFoundException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException,
            NoSuchMethodException, NoSuchFieldException, InstantiationException {
        // First set up IpAssignment to STATIC.
        Object ipAssignment = getEnumValue(
                "android.net.IpConfiguration$IpAssignment", "STATIC");
        callMethod(config, "setIpAssignment",
                new String[] { "android.net.IpConfiguration$IpAssignment" },
                new Object[] { ipAssignment });

        // Then 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);
        ArrayList aa = (ArrayList) getField(staticIpConfig,
                "dnsServers");
        aa.clear();
        for (int i = 0; i < dns.length; i++)
            aa.add(dns[i]);
        callMethod(config, "setStaticIpConfiguration",
                new String[] { "android.net.StaticIpConfiguration" },
                new Object[] { staticIpConfig });
        System.out.println("conconconm" + config);
        int updateNetwork = manager.updateNetwork(config);
        boolean saveConfiguration = manager.saveConfiguration();
        System.out.println("updateNetwork" + updateNetwork + saveConfiguration);

        System.out.println("ttttttttttt" + "  ");

        int netId = manager.addNetwork(config);
        manager.disableNetwork(netId);
        boolean  flag  = manager.enableNetwork(netId, true);
        Log.e("netId",netId+"");
        Log.e("flag",flag+"");

    }



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



    @SuppressWarnings({ "rawtypes", "unchecked" })
    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 enumClz = (Class) 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 Object getField(Object object, String fieldName)
            throws IllegalAccessException, IllegalArgumentException,
            NoSuchFieldException {
        Field field = object.getClass().getDeclaredField(fieldName);
        Object out = field.get(object);
        return out;
    }



    @SuppressWarnings("rawtypes")
    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);
    }


    public String intToIp(int ipAddress) {
        return ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "."
                + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));

    }
    //     set                   :
    public static String int2ip(int ip) {
        StringBuilder sb = new StringBuilder();
        sb.append(String.valueOf((int) (ip & 0xff)));
        sb.append('.');
        sb.append(String.valueOf((int) ((ip >> 8) & 0xff)));
        sb.append('.');
        sb.append(String.valueOf((int) ((ip >> 16) & 0xff)));
        sb.append('.');
        sb.append(String.valueOf((int) ((ip >> 24) & 0xff)));
        return sb.toString();
    }

}

좋은 웹페이지 즐겨찾기