Android WIFI热点&WAP网络访问代理

WIFI热点

package hillfly.wifichat.util;

import hillfly.wifichat.common.BaseApplication;
import hillfly.wifichat.consts.WifiApConst;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;

import org.apache.http.conn.util.InetAddressUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
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.Handler;
import android.os.Message;

/**
 * Wifi 工具类
 * 
 * 封装了Wifi的基础操作方法,方便获取Wifi连接信息以及操作Wifi
 */

public class WifiUtils {
    private static final Logger logger = Logger.getLogger(WifiUtils.class);
    private static Context mContext = BaseApplication.getInstance();
    private static WifiManager mWifiManager = (WifiManager) mContext
            .getSystemService(Context.WIFI_SERVICE);

    public static enum WifiCipherType {
        WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
    }

    public static void startWifiAp(String ssid, String passwd, final Handler handler) {
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }

        startAp(ssid, passwd);

        SchedulesUtils schedulesThread = new SchedulesUtils() {
            @Override
            public void doTimerCheckWork() {

                if (isWifiApEnabled()) {
                    // LogUtils.v("WifiAp enabled success!");
                    Message msg = handler.obtainMessage(WifiApConst.ApCreateApSuccess);
                    handler.sendMessage(msg);
                    this.exit();
                }
                else {
                    // LogUtils.v("WifiAp enabled failed!");
                }
            }

            @Override
            public void doTimeOutWork() {
                // TODO Auto-generated method stub
                this.exit();
            }
        };
        schedulesThread.start(10, 1000);

    }
    //创建热点
    private static void startAp(String ssid, String passwd) {
        Method method1 = null;
        try {
            method1 = mWifiManager.getClass().getMethod("setWifiApEnabled",
                    WifiConfiguration.class, boolean.class);
            WifiConfiguration netConfig = new WifiConfiguration();

            netConfig.SSID = ssid;
            netConfig.preSharedKey = passwd;

            netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

            method1.invoke(mWifiManager, netConfig, true);

        }
        catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
   //关闭wifi
    public static void closeWifiAp() {
        if (isWifiApEnabled()) {
            try {
                Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
                method.setAccessible(true);

                WifiConfiguration config = (WifiConfiguration) method.invoke(mWifiManager);

                Method method2 = mWifiManager.getClass().getMethod("setWifiApEnabled",
                        WifiConfiguration.class, boolean.class);
                method2.invoke(mWifiManager, config, false);
            }
            catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
   //检测wifi热点是否可用
    public static boolean isWifiApEnabled() {
        try {
            Method method = mWifiManager.getClass().getMethod("isWifiApEnabled");
            method.setAccessible(true);
            return (Boolean) method.invoke(mWifiManager);

        }
        catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
    //获取wifi或者wifi热点状态信息(值3和13表示可以使用)
    public static int getWifiApStateInt() {
        try {
            int i = ((Integer) mWifiManager.getClass().getMethod("getWifiApState", new Class[0])
                    .invoke(mWifiManager, new Object[0])).intValue();
            return i;
        }
        catch (Exception localException) {
        }
        return 4;
    }

    /**
     * 判断是否连接上wifi或者wifi热点
     * 
     * @return boolean值(isConnect),对应已连接(true)和未连接(false)
     */
    public static boolean isWifiConnect() {
        NetworkInfo mNetworkInfo = ((ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE))
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mNetworkInfo.isConnected();
    }
     //wifi或者wifi热点是否可以使用
    public static boolean isWifiEnabled() {
        return mWifiManager.isWifiEnabled();
    }

    public static void OpenWifi() {
        if (!mWifiManager.isWifiEnabled())
            mWifiManager.setWifiEnabled(true);
    }

    public static void closeWifi() {
        mWifiManager.setWifiEnabled(false);
    }

    public static void addNetwork(WifiConfiguration paramWifiConfiguration) {
        int i = mWifiManager.addNetwork(paramWifiConfiguration);
        mWifiManager.enableNetwork(i, true);
    }

    public static void removeNetwork(int netId) {
        if (mWifiManager != null) {
            mWifiManager.removeNetwork(netId);
            mWifiManager.saveConfiguration();
        }
    }

    /**
     * Function: 连接Wifi热点 <br>
     * 
     * @date 2015年2月14日 上午11:17
     * @change hillfly
     * @version 1.0
     * @param SSID
     * @param Password
     * @param Type
     * <br>
     *            没密码: {@linkplain WifiCipherType#WIFICIPHER_NOPASS}<br>
     *            WEP加密: {@linkplain WifiCipherType#WIFICIPHER_WEP}<br>
     *            WPA加密: {@linkplain WifiCipherType#WIFICIPHER_WPA}<br>
     * @return true:连接成功;false:连接失败
     */
    public static boolean connectWifi(String SSID, String Password, WifiCipherType Type) {
        if (!isWifiEnabled()) {
            return false;
        }
        // 开启wifi需要一段时间,要等到wifi状态变成WIFI_STATE_ENABLED
        while (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
            try {
                // 避免程序不停循环
                Thread.currentThread();
                Thread.sleep(500);
            }
            catch (InterruptedException ie) {
            }
        }

        WifiConfiguration wifiConfig = createWifiInfo(SSID, Password, Type);
        if (wifiConfig == null) {
            return false;
        }

        WifiConfiguration tempConfig = isExsits(SSID);

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

        int netID = mWifiManager.addNetwork(wifiConfig);

        // 断开连接
        mWifiManager.disconnect();
        
        // 设置为true,使其他的连接断开
        boolean bRet = mWifiManager.enableNetwork(netID, true);
        mWifiManager.reconnect();
        return bRet;
    }

    public static void disconnectWifi(int paramInt) {
        mWifiManager.disableNetwork(paramInt);
    }

    public static void startScan() {
        mWifiManager.startScan();
    }

    private static WifiConfiguration createWifiInfo(String SSID, String Password,
            WifiCipherType Type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";
        if (Type == WifiCipherType.WIFICIPHER_NOPASS) {
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == WifiCipherType.WIFICIPHER_WEP) {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            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 == 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);

        }
        else {
            return null;
        }
        return config;
    }

    public static String getApSSID() {
        try {
            Method localMethod = mWifiManager.getClass().getDeclaredMethod(
                    "getWifiApConfiguration", new Class[0]);
            if (localMethod == null)
                return null;
            Object localObject1 = localMethod.invoke(mWifiManager, new Object[0]);
            if (localObject1 == null)
                return null;
            WifiConfiguration localWifiConfiguration = (WifiConfiguration) localObject1;
            if (localWifiConfiguration.SSID != null)
                return localWifiConfiguration.SSID;
            Field localField1 = WifiConfiguration.class.getDeclaredField("mWifiApProfile");
            if (localField1 == null)
                return null;
            localField1.setAccessible(true);
            Object localObject2 = localField1.get(localWifiConfiguration);
            localField1.setAccessible(false);
            if (localObject2 == null)
                return null;
            Field localField2 = localObject2.getClass().getDeclaredField("SSID");
            localField2.setAccessible(true);
            Object localObject3 = localField2.get(localObject2);
            if (localObject3 == null)
                return null;
            localField2.setAccessible(false);
            String str = (String) localObject3;
            return str;
        }
        catch (Exception localException) {
        }
        return null;
    }

    public static String getBSSID() {
        WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
        return mWifiInfo.getBSSID();
    }

    public static String getSSID() {
        WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
        return mWifiInfo.getSSID();
    }

    public static String getLocalIPAddress() {
        WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
        return intToIp(wifiInfo.getIpAddress());
    }

    public static String getGPRSLocalIPAddress() {
        try {
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            while (en.hasMoreElements()) {
                NetworkInterface nif = en.nextElement();
                Enumeration<InetAddress> enumIpAddr = nif.getInetAddresses();
                while (enumIpAddr.hasMoreElements()) {
                    InetAddress mInetAddress = enumIpAddr.nextElement();
                    if (!mInetAddress.isLoopbackAddress()
                            && InetAddressUtils.isIPv4Address(mInetAddress.getHostAddress())) {
                        return mInetAddress.getHostAddress();
                    }
                }
            }
        }
        catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getServerIPAddress() {
        DhcpInfo mDhcpInfo = mWifiManager.getDhcpInfo();
        return intToIp(mDhcpInfo.gateway);
    }

    public static String getBroadcastAddress() {
        System.setProperty("java.net.preferIPv4Stack", "true");
        try {
            for (Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces(); niEnum
                    .hasMoreElements();) {
                NetworkInterface ni = niEnum.nextElement();
                if (!ni.isLoopback()) {
                    for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
                        if (interfaceAddress.getBroadcast() != null) {
                            logger.d(interfaceAddress.getBroadcast().toString().substring(1));
                            return interfaceAddress.getBroadcast().toString().substring(1);
                        }
                    }
                }
            }
        }
        catch (SocketException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String getMacAddress() {
        WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
        if (mWifiInfo == null)
            return "NULL";
        return mWifiInfo.getMacAddress();
    }

    public static int getNetworkId() {
        WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
        if (mWifiInfo == null)
            return 0;
        return mWifiInfo.getNetworkId();
    }

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

    public static List<ScanResult> getScanResults() {
        return mWifiManager.getScanResults();
    }

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

    private static String intToIp(int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "."
                + ((i >> 24) & 0xFF);
    }
}

APN+WAP网络代理

Java Http连接中(HttpURLConnection)中使用代理(Proxy)及其验证(Authentication)

在2g和3g手机时代,一个重要的角色是gprs流量,好处是分布广泛,坏处是价格昂贵网速奇慢。

能分配这种流量的只有移动电信运营商才有,你懂得。

/**
	 * 检查代理,是否cnwap接入
	 */
	public static  Proxy detectProxy() {
	        Proxy mProxy = null;
		ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		//获得当前cnwap的网络状态
		NetworkInfo ni = cm.getActiveNetworkInfo();
		//检查cnwap网络是否可以用
		if (ni != null && ni.isAvailable()
				&& ni.getType() == ConnectivityManager.TYPE_MOBILE) {
		        //获得默认代理主句地址
			String proxyHost = android.net.Proxy.getDefaultHost();
			//获得默认代理端口
			int port = android.net.Proxy.getDefaultPort();
			if (proxyHost != null) {
			        //获得当前手机的网络地址
				final InetSocketAddress sa = new InetSocketAddress(proxyHost,
						port);
				//生成代理对象
				mProxy = new Proxy(Proxy.Type.HTTP, sa);
			}
		}
		
		return mProxy;
	}
	 //获得代理连接对象
	public static HttpURLConnection getHttpConnection (String surl) throws Exception
	{
	    Proxy mProxy = detectProxy();
	    HttpURLConnection conn = null;
	    URL url = new URL(surl);
	    if(mProxy!=null)
	    {
	       conn = (HttpURLConnection) url.openConnection(mProxy);
	    }else{
	      conn = (HttpURLConnection) url.openConnection();
	    }
	    
	    return conn;
	}

这种cnwap代理方式是昂贵的,所以一般不推荐使用这种方式请求网络数据

关于APN的相关信息,我们通过如下方式获取

package com.hust.iprai;  
  
import android.content.ContentResolver;  
import android.content.Context;  
import android.database.Cursor;  
import android.net.ConnectivityManager;  
import android.net.NetworkInfo;  
import android.net.Uri;  
  
public class APNManager {  
  
    public static final Uri PREFERRED_APN_URI;  
  
    private String mApn; // 接入点名称   
  
    private String mPort; // 端口号   
  
    private String mProxy; // 代理服务器   
  
    private boolean mUseWap; // 是否正在使用WAP   
  
    static {  
        
        //取得全部的APN列表:content://telephony/carriers;
        //取得当前设置的APN:content://telephony/carriers/preferapn;
        //取得current=1的APN:content://telephony/carriers/current;
        PREFERRED_APN_URI = Uri.parse("content://telephony/carriers/preferapn"); // 取得当前设置的APN  
    }  
  
    public APNManager(Context context) {  
        checkNetworkType(context);  
    }  
  
    /** 
     * 获得当前设置的APN相关参数 
     * @param context 
     */  
    private void checkApn(Context context) {  
        ContentResolver contentResolver = context.getContentResolver();  
        Uri uri = PREFERRED_APN_URI;  
        String[] apnInfo = new String[3];  
        apnInfo[0] = "apn";  
        apnInfo[1] = "proxy";  
        apnInfo[2] = "port";  
  
        Cursor cursor = contentResolver.query(uri, apnInfo, null, null, null);  
        if (cursor != null) {  
            while (cursor.moveToFirst()) {  
                this.mApn = cursor.getString(cursor.getColumnIndex("apn"));  
                this.mProxy = cursor.getString(cursor.getColumnIndex("proxy"));  
                this.mPort = cursor.getString(cursor.getColumnIndex("port"));  
  
                // 代理为空   
                if ((this.mProxy == null) || (this.mProxy.length() <= 0)) {  
                    String apn = this.mApn.toUpperCase();  
                      
                    // 中国移动WAP设置:APN:CMWAP;代理:10.0.0.172;端口:80   
                    // 中国联通WAP设置:APN:UNIWAP;代理:10.0.0.172;端口:80   
                    // 中国联通WAP设置(3G):APN:3GWAP;代理:10.0.0.172;端口:80   
                    if ((apn.equals("CMWAP")) || (apn.equals("UNIWAP")) || (apn.equals("3GWAP"))) {  
                        this.mUseWap = true;  
                        this.mProxy = "10.0.0.172";  
                        this.mPort = "80";  
                        break;  
                    }  
                      
                    // 中国电信WAP设置:APN(或者接入点名称):CTWAP;代理:10.0.0.200;端口:80   
                    if (apn.equals("CTWAP")) {  
                        this.mUseWap = true;  
                        this.mProxy = "10.0.0.200";  
                        this.mPort = "80";  
                        break;  
                    }  
                      
                }  
                this.mPort = "80";  
                this.mUseWap = true;  
                break;  
            }  
  
        }  
  
        this.mUseWap = false;  
        cursor.close();  
    }  
  
    /** 
     * 检测当前使用的网络类型是WIFI还是WAP 
     * @param context 
     */  
    private void checkNetworkType(Context context) {  
        NetworkInfo networkInfo = ((ConnectivityManager) context  
                .getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();  
        if (networkInfo != null) {  
            if (!"wifi".equals(networkInfo.getTypeName().toLowerCase())) {  
                checkApn(context);  
                return;  
            }  
            this.mUseWap = false;  
        }  
    }  
  
    /** 
     * 判断当前网络连接状态 
     * @param context 
     * @return 
     */  
    public static boolean isNetworkConnected(Context context) {  
        NetworkInfo networkInfo = ((ConnectivityManager) context  
                .getApplicationContext().getSystemService("connectivity"))  
                .getActiveNetworkInfo();  
        if (networkInfo != null) {  
            return networkInfo.isConnectedOrConnecting();  
        }  
        return false;  
    }  
  
    public String getApn() {  
        return this.mApn;  
    }  
  
    public String getProxy() {  
        return this.mProxy;  
    }  
  
    public String getProxyPort() {  
        return this.mPort;  
    }  
  
    public boolean isWapNetwork() {  
        return this.mUseWap;  
    }  
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值