Android Wifi IP 设置

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;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

public class WifiActivity extends Activity implements OnClickListener{
	protected static final String TAG = "WifiActivity";
	
	public final static String KEY_WIFI_PRIORITY = "wifi_priority";
	public final static String KEY_WIFI_STATIC_IP = "wifi_static_ip";
	
	WifiP2pManager mManager;
	Channel mChannel;
	BroadcastReceiver mReceiver;
	IntentFilter mIntentFilter;
	private WifiManager mWifiManager;
	private List<ScanResult> mListResult;
	private WifiAdapter mWifiAdapter;
	private ListView mList;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.wifi_list);
        ImageButton btn = (ImageButton)findViewById(R.id.back);
        btn.setOnClickListener(this);
        mList = (ListView)findViewById(R.id.list_view);
        mReceiver = new WifiReceiver(new WifiScanListener() {
			
			@Override
			public void suppStateChange() {
				
			}
			
			@Override
			public void stateChange() {
				
			}
			
			@Override
			public void endScan() {
				endScanWifi(mWifiManager.getScanResults());				
			}
		});
        
        mIntentFilter = new IntentFilter();
        
        mIntentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
        mIntentFilter.addAction("android.net.wifi.SCAN_RESULTS");
        mIntentFilter.addAction("android.net.wifi.supplicant.STATE_CHANGE");
        
        mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);        
        mWifiManager.setWifiEnabled(true);
        mWifiAdapter = new WifiAdapter(this, null);
        mList.setAdapter(mWifiAdapter);
        
    }
    
//    void showLog(String msg) {
//		new AlertDialog.Builder(this).setTitle(R.string.alert_dialog_prompt).setMessage(msg).show();
//	}

	void promptMessage(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
	}
    
    public void showEditWifi(final ScanResult sr){
    	LayoutInflater factory = LayoutInflater.from(this);
		final View textEntryView = factory.inflate(R.layout.dialog_wifi_setting, null);
		new AlertDialog.Builder(this).setIconAttribute(android.R.attr.dialogIcon).setTitle(sr.SSID).setView(textEntryView).setCancelable(false)
				.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						try {
							EditText edtWifiPwd = (EditText) textEntryView.findViewById(R.id.edt_wifi_pwd);
							EditText edtStaticIp = (EditText) textEntryView.findViewById(R.id.edt_static_ip);
							EditText edtStaticGateway = (EditText) textEntryView.findViewById(R.id.edt_static_gateway);
							EditText edtStaticNetmask = (EditText) textEntryView.findViewById(R.id.edt_static_netmask);
							EditText edtStaticDns = (EditText) textEntryView.findViewById(R.id.edt_static_dns);
							
							String wifiPwd = edtWifiPwd.getText().toString().trim();
							String ip = edtStaticIp.getText().toString().trim();
							String gateway = edtStaticGateway.getText().toString().trim();
							String prefixLength = edtStaticNetmask.getText().toString().trim();
							String dns = edtStaticDns.getText().toString().trim();
							
							saveStaticWifiConfig(sr,wifiPwd,ip,Integer.parseInt(prefixLength));
						}catch (IllegalArgumentException e) {
							promptMessage(getString(R.string.system_wifi_ip_error));
						} catch (Exception e) {
							e.printStackTrace();
							promptMessage(getString(R.string.system_wifi_setting_error));
						}
					}
				}).setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
					}
				}).create().show();
		
		try {
			WifiConfiguration historyWifiConfig = getHistoryWifiConfig(sr.SSID);
			EditText edtWifiPwd = (EditText) textEntryView.findViewById(R.id.edt_wifi_pwd);
			EditText edtStaticIp = (EditText) textEntryView.findViewById(R.id.edt_static_ip);
			EditText edtStaticGateway = (EditText) textEntryView.findViewById(R.id.edt_static_gateway);
			EditText edtStaticNetmask = (EditText) textEntryView.findViewById(R.id.edt_static_netmask);
			EditText edtStaticDns = (EditText) textEntryView.findViewById(R.id.edt_static_dns);
			
	    	if(historyWifiConfig != null){    		
	    		InetAddress address = getIpAddress(historyWifiConfig);
	    		if(address != null){
	    			edtStaticIp.setText(address.getHostAddress());
	    			address = null;
	    		}
	    		address = getGateway(historyWifiConfig);
	    		if(address != null){
	    			edtStaticGateway.setText(address.getHostAddress());
	    			address = null;
	    		}
	    		address = getDNS(historyWifiConfig);
	    		if(address != null){
	    			edtStaticDns.setText(address.getHostAddress());
	    			address = null;
	    		}
	    		edtStaticNetmask.setText(getNetworkPrefixLength(historyWifiConfig));			
				
	    	}
	    	
	    	if(TextUtils.isEmpty(edtStaticIp.getText().toString().trim())){
	    		String ipString = SmartHomePreference.getStringProperty(KEY_WIFI_STATIC_IP);
	    		int intIp = inetAddressToInt(InetAddress.getByName(ipString)); 
	    		String dns = (intIp & 0xFF ) + "." + ((intIp >> 8 ) & 0xFF) + "." + ((intIp >> 16 ) & 0xFF) + ".1";
	    		
	    		edtStaticIp.setText(ipString);
	    		edtStaticNetmask.setText("24");
	    		edtStaticGateway.setText(dns);
	    		edtStaticDns.setText(dns);	    		
	    	}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
    }
    
    /**
     * 设置wifi,编辑静态IP
     * @param sr
     * @param pwd
     * @param ip
     * @throws Exception
     */
    public void saveStaticWifiConfig(final ScanResult sr,String pwd, String ip,int networkPrefixLength) throws Exception{  
    	InetAddress intetAddress  = InetAddress.getByName(ip);
    	int intIp = inetAddressToInt(intetAddress);    	
    	WifiConfiguration historyWifiConfig = getHistoryWifiConfig(sr.SSID);        	
    	if(historyWifiConfig == null){
    		historyWifiConfig = createComWifiConfig(sr.SSID,pwd);    		
    	}else{
    		if(!TextUtils.isEmpty(pwd)){
    			historyWifiConfig.preSharedKey = "\""+ pwd + "\"";  
    		}
    	}
    	
    	String dns = (intIp & 0xFF ) + "." + ((intIp >> 8 ) & 0xFF) + "." + ((intIp >> 16 ) & 0xFF) + ".1";
    	setIpAssignment("STATIC", historyWifiConfig); //"STATIC" or "DHCP" for dynamic setting
        setIpAddress(intetAddress, networkPrefixLength, historyWifiConfig);
        setGateway(InetAddress.getByName(dns), historyWifiConfig);
        setDNS(InetAddress.getByName(dns), historyWifiConfig);          
        
        mWifiManager.removeNetwork(historyWifiConfig.networkId);
        int netId = mWifiManager.addNetwork(historyWifiConfig);
		mWifiManager.enableNetwork(netId, true);
        mWifiManager.updateNetwork(historyWifiConfig); //apply the setting
        SmartHomePreference.setProperty(WifiActivity.KEY_WIFI_PRIORITY, sr.SSID);
        
        mWifiManager.startScan();
	}
    
    
    /***
     * Convert a IPv4 address from an InetAddress to an integer
     * @param inetAddr is an InetAddress corresponding to the IPv4 address
     * @return the IP address as an integer in network byte order
     */
    public static int inetAddressToInt(InetAddress inetAddr)
            throws IllegalArgumentException {
        byte [] addr = inetAddr.getAddress();
        if (addr.length != 4) {
            throw new IllegalArgumentException("Not an IPv4 address");
        }
        return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) |
                ((addr[1] & 0xff) << 8) | (addr[0] & 0xff);
    }
    
    public void editStaticWifiConfig(final ScanResult sr,String pwd, String ip, String gateway,int prefixLength,String dns) throws Exception{        
    	WifiConfiguration historyWifiConfig = getHistoryWifiConfig(sr.SSID);
    	
    	if(historyWifiConfig == null){
    		historyWifiConfig = createComWifiConfig(sr.SSID,pwd);
    		int netId = mWifiManager.addNetwork(historyWifiConfig);
    		mWifiManager.enableNetwork(netId, true);
    	}
    	
        setIpAssignment("STATIC", historyWifiConfig); //"STATIC" or "DHCP" for dynamic setting
        setIpAddress(InetAddress.getByName(ip), prefixLength, historyWifiConfig);
        setGateway(InetAddress.getByName(gateway), historyWifiConfig);
        setDNS(InetAddress.getByName(dns), historyWifiConfig);
        
        mWifiManager.updateNetwork(historyWifiConfig); //apply the setting
	}
    
    public void editDhcpWifiConfig(final ScanResult sr,String pwd) throws Exception{        
    	WifiConfiguration historyWifiConfig = getHistoryWifiConfig(sr.SSID);
    	
    	if(historyWifiConfig == null){
    		historyWifiConfig = createComWifiConfig(sr.SSID,pwd);
    		int netId = mWifiManager.addNetwork(historyWifiConfig);
    		mWifiManager.enableNetwork(netId, true);
    	}
    	
        setIpAssignment("DHCP", historyWifiConfig); //"STATIC" or "DHCP" for dynamic setting
        
        mWifiManager.updateNetwork(historyWifiConfig); //apply the setting
	}

    /**
     *  新建wifi配置项
     * @param ssid
     * @param pwd
     * @return
     */
    public WifiConfiguration createComWifiConfig(String ssid,String pwd){
    	WifiConfiguration wc = new WifiConfiguration();
        wc.SSID = "\"" + ssid + "\"";      				//配置wifi的SSID,即该热点的名称,如:TP-link_xxx
        wc.preSharedKey = "\""+ pwd + "\"";            //该热点的密码
        wc.hiddenSSID = true;
        wc.status = WifiConfiguration.Status.ENABLED;
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        return wc;
    }
    
    /**
     * 查找已经设置好的Wifi
     * @param ssid
     * @return
     */
    public WifiConfiguration getHistoryWifiConfig(String ssid){
    	List<WifiConfiguration> localList = mWifiManager.getConfiguredNetworks();
        for(WifiConfiguration wc : localList){
        	if(("\"" + ssid + "\"").equals(wc.SSID)){
        		return wc;
        	}
        	mWifiManager.disableNetwork(wc.networkId);
        }
        return null;
    }
  
	public static void setIpAssignment(String assign, WifiConfiguration wifiConf)throws SecurityException, IllegalArgumentException,NoSuchFieldException, IllegalAccessException {
		setEnumField(wifiConf, assign, "ipAssignment");
	}

	public 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);
	}

	public 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;
		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);
	}

	public static void setDNS(InetAddress dns, WifiConfiguration wifiConf) throws SecurityException, IllegalArgumentException,NoSuchFieldException, IllegalAccessException {
		Object linkProperties = getField(wifiConf, "linkProperties");
		if (linkProperties == null)
			return;
		ArrayList<InetAddress> mDnses = (ArrayList<InetAddress>) getDeclaredField(linkProperties, "mDnses");
		mDnses.clear(); // or add a new dns address , here I just want to replace DNS1
		mDnses.add(dns);
	}
	
	public static String getNetworkPrefixLength(WifiConfiguration wifiConf) {
		String address = "";
		try {
			Object linkProperties = getField(wifiConf, "linkProperties");
			if (linkProperties == null)
				return null;
			
			if (linkProperties != null){
				ArrayList mLinkAddresses = (ArrayList) getDeclaredField(linkProperties,"mLinkAddresses");
				if(mLinkAddresses != null && mLinkAddresses.size() > 0){
					Object linkAddressObj = mLinkAddresses.get(0);
					address = linkAddressObj.getClass().getMethod("getNetworkPrefixLength",  new Class[]{}).invoke(linkAddressObj,null) + "";
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return address;
	}
	
	public static InetAddress getIpAddress(WifiConfiguration wifiConf) {
		InetAddress address = null;
		try {
			Object linkProperties = getField(wifiConf, "linkProperties");
			if (linkProperties == null)
				return null;
			
			if (linkProperties != null){
				ArrayList mLinkAddresses = (ArrayList) getDeclaredField(linkProperties,"mLinkAddresses");
				if(mLinkAddresses != null && mLinkAddresses.size() > 0){
					Object linkAddressObj = mLinkAddresses.get(0);
					address = (InetAddress)linkAddressObj.getClass().getMethod("getAddress",  new Class[]{}).invoke(linkAddressObj,null);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return address;
	}

	public static InetAddress getGateway(WifiConfiguration wifiConf)  {
		InetAddress address = null;
		try {
			Object linkProperties = getField(wifiConf, "linkProperties");
			
			if (linkProperties != null){
				ArrayList mRoutes = (ArrayList) getDeclaredField(linkProperties,"mRoutes");
				if(mRoutes != null && mRoutes.size() > 0){
					Object linkAddressObj = mRoutes.get(0);
					address = (InetAddress)linkAddressObj.getClass().getMethod("getGateway",  new Class[]{}).invoke(linkAddressObj,null);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return address;
	}

	public static InetAddress getDNS(WifiConfiguration wifiConf) {
		InetAddress address = null;
		try {
			Object linkProperties = getField(wifiConf, "linkProperties");
			
			if (linkProperties != null){
				ArrayList<InetAddress> mDnses = (ArrayList<InetAddress>) getDeclaredField(linkProperties, "mDnses");
				if(mDnses != null && mDnses.size() > 0){
					address = (InetAddress)mDnses.get(0);				
				}
			}		
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return address;
	}

	public 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;
	}

	public 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;
	}

	public 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<Enum>) f.getType(), value));
	}


    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mReceiver, mIntentFilter);
        if(mWifiManager != null) mWifiManager.startScan();
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);        
    }

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
//			if(mWifiManager != null) mWifiManager.startScan();
			finish();
			break;

		default:
			break;
		}
	}
	
	public void endScanWifi(final List<ScanResult> list){
		runOnUiThread(new Runnable() {			
			@Override
			public void run() {
				if(mWifiAdapter != null){
					mWifiAdapter.setList(list);
					mWifiAdapter.notifyDataSetChanged();
				}	
			}
		});
			
	}
}

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值