android 连接wifi案例

1、xml布局文件:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.helloword.WifiTestActivity" >

     <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="10dp"
        android:orientation="vertical"
        android:paddingLeft="16dp"
        android:paddingRight="16dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="10dp"
            android:orientation="vertical">

            <TextView
                android:id="@+id/wifi_state"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:hint="wifi state"
                android:textColor="@android:color/black" />

            <TextView
                android:id="@+id/wifi_name"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:hint="wifi name"
                android:textColor="@android:color/black" />

            <TextView
                android:id="@+id/wifi_mac"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:hint="mac"
                android:textColor="@android:color/black" />

            <TextView
                android:id="@+id/ip_address"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:hint="ip address"
                android:textColor="@android:color/black" />
            <TextView
                android:id="@+id/ip_gateway"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:hint="gateway"
                android:textColor="@android:color/black" />
            
            <EditText 
                android:id="@+id/et_pwd"
                android:layout_width="360dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:hint="wifi密码"
            
                />
        </LinearLayout>
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:background="@android:color/black" />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:orientation="horizontal">

            <Button
                android:id="@+id/search_wifi"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="search wifi" />

            <Button
                android:id="@+id/connect_wifi"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="connect" />


        </LinearLayout>

        <ListView
            android:id="@+id/list_wifi"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="10dp"></ListView>
    </LinearLayout>

    <FrameLayout
        android:id="@+id/progressbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:visibility="gone">

        <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </FrameLayout>
    
</FrameLayout>

2、适配xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:textColor="@android:color/black"
        android:text="test"
        android:id="@+id/wifi_item_name"
        android:layout_margin="5dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

3、activity

package com.example.helloword;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.example.helloword.service.TimerService;
import com.example.helloword.service.WifiTimerService;
import com.example.helloword.utils.WifiAutoConnectManager;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class WifiTestActivity extends Activity implements View.OnClickListener {

    EditText et_pwd;
    TextView mWifiState;//wifi状态
    TextView mWifiName;//Wi-Fi名称
    TextView mMac;//物理地址
    TextView mIP;//ip地址
    TextView mGateway;//网关地址
    ListView mListWifi;//Wi-Fi列表
    Button mBtnSearch;//搜索Wi-Fi
    Button mBtnConnect;//连接Wi-Fi
    WifiListAdapter mWifiListAdapter;
    public static final int WIFI_SCAN_PERMISSION_CODE = 2;
    WorkAsyncTask mWorkAsyncTask = null;
    ConnectAsyncTask mConnectAsyncTask = null;
    List<ScanResult> mScanResultList = new ArrayList<ScanResult>();
    public static String ssid = "";
    WifiAutoConnectManager.WifiCipherType type = WifiAutoConnectManager.WifiCipherType.WIFICIPHER_NOPASS;
    public static String password = "";//"hyc888888";
    FrameLayout progressbar;
    boolean isLinked = false;

    String gateway = "";
    String mac = "";
    
    /**
     * 处理信号量改变或者扫描结果改变的广播
     */
    private BroadcastReceiver mWifiSearchBroadcastReceiver;
    private IntentFilter mWifiSearchIntentFilter;
    private BroadcastReceiver mWifiConnectBroadcastReceiver;
    private IntentFilter mWifiConnectIntentFilter;
    private WifiAutoConnectManager mWifiAutoConnectManager;
    
        
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wifi_test);
        
        Intent intent = new Intent(WifiTestActivity.this, WifiTimerService.class);
          //使用Intent传值
        intent.putExtra("key","value");
        startService(intent);
        
        intiView();
        
        //初始化wifi工具
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        mWifiAutoConnectManager = WifiAutoConnectManager.newInstance(wifiManager);

//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//            // 获取wifi连接需要定位权限,没有获取权限
//            ActivityCompat.requestPermissions(this, new String[]{
//                    Manifest.permission.ACCESS_COARSE_LOCATION,
//            }, WIFI_SCAN_PERMISSION_CODE);
//            return;
//        }
        
        
        //设置监听wifi状态变化广播
        initWifiSate();
    }

    

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
        case R.id.search_wifi:
            if (mWorkAsyncTask != null) {
                mWorkAsyncTask.cancel(true);
                mWorkAsyncTask = null;
            }
            mWorkAsyncTask = new WorkAsyncTask();
            mWorkAsyncTask.execute();
            break;
        case R.id.connect_wifi:
            if (ssid.equals(WifiAutoConnectManager.getSSID())) {
                return;
            }
            String pwdString = et_pwd.getText().toString().trim();
            if(TextUtils.isEmpty(pwdString)){
                Toast.makeText(WifiTestActivity.this, "请先填写wifi密码", Toast.LENGTH_SHORT).show();
                return;
            }
            
            password = pwdString;
            
            if (mConnectAsyncTask != null) {
                mConnectAsyncTask.cancel(true);
                mConnectAsyncTask = null;
            }
            mConnectAsyncTask = new ConnectAsyncTask(ssid, password, type);
            mConnectAsyncTask.execute();
            break;
        default:
            break;
    }
        
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mWifiSearchBroadcastReceiver, mWifiSearchIntentFilter);
        registerReceiver(mWifiConnectBroadcastReceiver, mWifiConnectIntentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mWifiSearchBroadcastReceiver);
        unregisterReceiver(mWifiConnectBroadcastReceiver);
    }
    
    private void initWifiSate() {
        
        //wifi 搜索结果接收广播
        mWifiSearchBroadcastReceiver = new BroadcastReceiver() {
            
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {// 扫描结果改表
                    mScanResultList = WifiAutoConnectManager.getScanResults();
                    if (mWifiListAdapter != null) {
                        
                        mWifiListAdapter.setmWifiList(mScanResultList);
                        

                        mWifiListAdapter.notifyDataSetChanged();
                        
                    }
                }
            }

            
            
            
            
        };
        
        mWifiSearchIntentFilter = new IntentFilter();
        mWifiSearchIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        mWifiSearchIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        mWifiSearchIntentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);

        //wifi 状态变化接收广播
        mWifiConnectBroadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                    int wifState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
                    if (wifState != WifiManager.WIFI_STATE_ENABLED) {
                        Toast.makeText(WifiTestActivity.this, "没有wifi", Toast.LENGTH_SHORT).show();
                    }
                } else if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
                    int linkWifiResult = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, 123);
                    Log.e("wifidemo", ssid + "linkWifiResult:" + linkWifiResult);
                    if (linkWifiResult == WifiManager.ERROR_AUTHENTICATING) {
                        Log.e("wifidemo", ssid + "onReceive:密码错误");
                    }
                } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                    NetworkInfo.DetailedState state = ((NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO)).getDetailedState();
                    setWifiState(state);
                }
            }
        };
        
        mWifiConnectIntentFilter = new IntentFilter();
        mWifiConnectIntentFilter.addAction(WifiManager.ACTION_PICK_WIFI_NETWORK);
        mWifiConnectIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        mWifiConnectIntentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        mWifiConnectIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
    
    }

    /**
     * 显示wifi状态
     *
     * @param state
     */
    @SuppressLint("NewApi")
    public void setWifiState(final NetworkInfo.DetailedState state) {
        if (state == NetworkInfo.DetailedState.AUTHENTICATING) {

        } else if (state == NetworkInfo.DetailedState.BLOCKED) {

        } else if (state == NetworkInfo.DetailedState.CONNECTED) {
            progressbar.setVisibility(View.GONE);
            isLinked = true;
            mWifiState.setText("wifi state:连接成功");
            mWifiName.setText("wifi name:" + WifiAutoConnectManager.getSSID());
            mIP.setText("ip address:" + WifiAutoConnectManager.getIpAddress());
            mGateway.setText("gateway:" + WifiAutoConnectManager.getGateway());
            mMac.setText("mac:" + WifiAutoConnectManager.getMacAddress());
            gateway = WifiAutoConnectManager.getGateway();
            mac = WifiAutoConnectManager.getMacAddress();
        } else if (state == NetworkInfo.DetailedState.CONNECTING) {
            isLinked = false;
            mWifiState.setText("wifi state:连接中...");
            mWifiName.setText("wifi name:" + WifiAutoConnectManager.getSSID());
            mIP.setText("ip address");
            mGateway.setText("gateway");
        } else if (state == NetworkInfo.DetailedState.DISCONNECTED) {
            isLinked = false;
            mWifiState.setText("wifi state:断开连接");
            mWifiName.setText("wifi name");
            mIP.setText("ip address");
            mGateway.setText("gateway");
        } else if (state == NetworkInfo.DetailedState.DISCONNECTING) {
            isLinked = false;
            mWifiState.setText("wifi state:断开连接中...");
        } else if (state == NetworkInfo.DetailedState.FAILED) {
            isLinked = false;
            mWifiState.setText("wifi state:连接失败");
        } else if (state == NetworkInfo.DetailedState.IDLE) {

        } else if (state == NetworkInfo.DetailedState.OBTAINING_IPADDR) {

        } else if (state == NetworkInfo.DetailedState.SCANNING) {

        } else if (state == NetworkInfo.DetailedState.SUSPENDED) {

        }
    }

    private void intiView() {
        
        progressbar = (FrameLayout) findViewById(R.id.progressbar);
        mWifiState = (TextView) findViewById(R.id.wifi_state);
        mWifiName = (TextView) findViewById(R.id.wifi_name);
        mMac = (TextView) findViewById(R.id.wifi_mac);
        mIP = (TextView) findViewById(R.id.ip_address);
        mGateway = (TextView) findViewById(R.id.ip_gateway);
        mListWifi = (ListView) findViewById(R.id.list_wifi);
        mBtnSearch = (Button) findViewById(R.id.search_wifi);
        mBtnConnect = (Button) findViewById(R.id.connect_wifi);
        
        et_pwd = (EditText) findViewById(R.id.et_pwd);
        
       
        

        mBtnSearch.setOnClickListener(this);
        mBtnConnect.setOnClickListener(this);

        mListWifi.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mWifiListAdapter.setSelectItem(i);
                
                mWifiListAdapter.notifyDataSetChanged();
                
                ScanResult scanResult = mScanResultList.get(i);
                ssid = scanResult.SSID;
                type = WifiAutoConnectManager.getCipherType(ssid);
            }
        });
    }
    
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case WIFI_SCAN_PERMISSION_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
                    // 不允许
                    Toast.makeText(this, "开启权限失败", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 获取wifi列表
     */
    private class WorkAsyncTask extends AsyncTask<Void, Void, List<ScanResult>> {
        private List<ScanResult> mScanResult = new ArrayList<>();

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressbar.setVisibility(View.VISIBLE);
        }

        @Override
        protected List<ScanResult> doInBackground(Void... params) {
            if (WifiAutoConnectManager.startStan()) {
                mScanResult = WifiAutoConnectManager.getScanResults();
            }
            List<ScanResult> filterScanResultList = new ArrayList<>();
            if (mScanResult != null) {
                for (ScanResult wifi : mScanResult) {
                    filterScanResultList.add(wifi);
                    Log.e("wifidemo", "doInBackground: wifi:" + wifi);
                }
            }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return filterScanResultList;
        }

        @Override
        protected void onPostExecute(final List<ScanResult> result) {
            super.onPostExecute(result);
            progressbar.setVisibility(View.GONE);
            mScanResultList = result;
            mWifiListAdapter = new WifiListAdapter(result, LayoutInflater.from(WifiTestActivity.this));
            
            mListWifi.setAdapter(mWifiListAdapter);

        }
    }

    /**
     * wifi列表适配器
     */
    class WifiListAdapter extends BaseAdapter {

        private List<ScanResult> mWifiList;
        private LayoutInflater mLayoutInflater;

        public WifiListAdapter(List<ScanResult> wifiList, LayoutInflater layoutInflater) {
            this.mWifiList = wifiList;
            this.mLayoutInflater = layoutInflater;
        }

        @Override
        public int getCount() {
            return mWifiList.size();
        }

        @Override
        public Object getItem(int position) {
            return mWifiList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                convertView = mLayoutInflater.inflate(R.layout.fragment_wifi_list_item, null);
            }
            ScanResult sr = mWifiList.get(position);
            convertView.setTag(sr);
            TextView textView = (TextView) convertView.findViewById(R.id.wifi_item_name);
            int numLevel = WifiAutoConnectManager.getSignalNumsLevel(sr.level, 5);
            String password = sr.capabilities;
            String text = "加密方式:";
            if (password.contains("WPA") || password.contains("wpa")) {
                password = "WPA";
            } else if (password.contains("WEP") || password.contains("wep")) {
                password = "WEP";
            } else {
                text = "";
                password = "";
            }
            textView.setText(sr.SSID + " " + text + password + "  信号强度:" + numLevel);
            convertView.setBackgroundColor(Color.WHITE);
            if (position == selectItem) {
                convertView.setBackgroundColor(Color.GRAY);
            }
            return convertView;
        }

        public void setSelectItem(int selectItem) {
            this.selectItem = selectItem;
        }

        private int selectItem = -1;

        public void setmWifiList(List<ScanResult> mWifiList) {
            this.mWifiList = mWifiList;
        }
    }


    /**
     * 连接指定的wifi
     */
    class ConnectAsyncTask extends AsyncTask<Void, Void, Boolean> {
        private String ssid;
        private String password;
        private WifiAutoConnectManager.WifiCipherType type;
        WifiConfiguration tempConfig;

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

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressbar.setVisibility(View.VISIBLE);
        }

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

                } catch (InterruptedException ie) {
                    Log.e("wifidemo", ie.toString());
                }
            }

            tempConfig = mWifiAutoConnectManager.isExsits(ssid);
            //禁掉所有wifi
            for (WifiConfiguration c : mWifiAutoConnectManager.wifiManager.getConfiguredNetworks()) {
                mWifiAutoConnectManager.wifiManager.disableNetwork(c.networkId);
            }
            
            if (tempConfig != null) {
                Log.d("wifidemo", ssid + "配置过!");
                boolean result = mWifiAutoConnectManager.wifiManager.enableNetwork(tempConfig.networkId, true);
                if (!isLinked && type != WifiAutoConnectManager.WifiCipherType.WIFICIPHER_NOPASS) {
                    try {
                        Thread.sleep(5000);//超过5s提示失败
                        if (!isLinked) {
                            Log.d("wifidemo", ssid + "连接失败!");
                          

  

                  Log.d("wifidemo", ssid + "连接失败!");
                  //mWifiAutoConnectManager.wifiManager.disableNetwork(tempConfig.networkId);

                  Log.d("wifidemo", "----------------"+ssid+"重新连接中.....");
                  //如果连接失败 删除原来的networkId 重新假如
                  mWifiAutoConnectManager.wifiManager.removeNetwork(tempConfig.networkId);
                  WifiConfiguration wifiConfig = mWifiAutoConnectManager.createWifiInfo(ssid, password, type);
                  int netID = mWifiAutoConnectManager.wifiManager.addNetwork(wifiConfig);
                  boolean enabled = mWifiAutoConnectManager.wifiManager.enableNetwork(netID, true);
                  Log.d("wifidemo", "enableNetwork status enable=" + enabled);
//



                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                Log.d("wifidemo", "result=" + result);
                return result;
            } else {
                Log.d("wifidemo", ssid + "没有配置过!");
                if (type != WifiAutoConnectManager.WifiCipherType.WIFICIPHER_NOPASS) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            final EditText inputServer = new EditText(WifiTestActivity.this);
                            new AlertDialog.Builder(WifiTestActivity.this)
                                    .setTitle("请输入密码")
                                    .setView(inputServer)
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .setPositiveButton("连接", new DialogInterface.OnClickListener() {

                                        public void onClick(DialogInterface dialog, int which) {
                                            password = inputServer.getText().toString();
                                            new Thread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    WifiConfiguration wifiConfig = mWifiAutoConnectManager.createWifiInfo(ssid, password,
                                                            type);
                                                    if (wifiConfig == null) {
                                                        Log.d("wifidemo", "wifiConfig is null!");
                                                        return;
                                                    }
                                                    Log.d("wifidemo", wifiConfig.SSID);

                                                    int netID = mWifiAutoConnectManager.wifiManager.addNetwork(wifiConfig);
                                                    boolean enabled = mWifiAutoConnectManager.wifiManager.enableNetwork(netID, true);
                                                    Log.d("wifidemo", "enableNetwork status enable=" + enabled);
//                                                    Log.d("wifidemo", "enableNetwork connected=" + mWifiAutoConnectManager.wifiManager.reconnect());
//                                                    mWifiAutoConnectManager.wifiManager.reconnect();
                                                }
                                            }).start();
                                        }
                                    }).show();
                        }
                    });
                } else {
                    WifiConfiguration wifiConfig = mWifiAutoConnectManager.createWifiInfo(ssid, password, type);
                    if (wifiConfig == null) {
                        Log.d("wifidemo", "wifiConfig is null!");
                        return false;
                    }
                    Log.d("wifidemo", wifiConfig.SSID);
                    int netID = mWifiAutoConnectManager.wifiManager.addNetwork(wifiConfig);
                    boolean enabled = mWifiAutoConnectManager.wifiManager.enableNetwork(netID, true);
                    Log.d("wifidemo", "enableNetwork status enable=" + enabled);
//                    Log.d("wifidemo", "enableNetwork connected=" + mWifiAutoConnectManager.wifiManager.reconnect());
//                    return mWifiAutoConnectManager.wifiManager.reconnect();
                    return enabled;
                }
                return false;


            }
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            mConnectAsyncTask = null;
        }
    }


    
    
}

4、WifiAutoConnectManager

package com.example.helloword.utils;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.util.Log;

public class WifiAutoConnectManager {
    
      private static final String TAG = WifiAutoConnectManager.class
                .getSimpleName();

        public static WifiManager wifiManager = null;
        private static WifiAutoConnectManager mWifiAutoConnectManager;

        // 定义几种加密方式,一种是WEP,一种是WPA,还有没有密码的情况
        public enum WifiCipherType {
            WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
        }

        // 构造函数
        private WifiAutoConnectManager(WifiManager wifiManager) {
            this.wifiManager = wifiManager;
        }

        public static WifiAutoConnectManager newInstance(WifiManager wifiManager) {
            if (mWifiAutoConnectManager == null) {
                mWifiAutoConnectManager = new WifiAutoConnectManager(wifiManager);
            }
            return mWifiAutoConnectManager;
        }


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

        /**
         * 创建wifi配置文件
         *
         * @param SSID
         * @param Password
         * @param Type
         * @return
         */
        public 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 + "\"";
            // config.SSID = SSID;
            // nopass
            if (Type == WifiCipherType.WIFICIPHER_NOPASS) {
                // config.wepKeys[0] = "";
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                // config.wepTxKeyIndex = 0;
            } else if (Type == WifiCipherType.WIFICIPHER_WEP) {// 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;
            } else if (Type == WifiCipherType.WIFICIPHER_WPA) {// wpa
                config.preSharedKey = "\"" + Password + "\"";
                config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                config.status = WifiConfiguration.Status.ENABLED;
            }
            return config;
        }

        // 打开wifi功能
        public boolean openWifi() {
            boolean bRet = true;
            if (!wifiManager.isWifiEnabled()) {
                bRet = wifiManager.setWifiEnabled(true);
            }
            return bRet;
        }

        // 关闭WIFI
        private void closeWifi() {
            if (wifiManager.isWifiEnabled()) {
                wifiManager.setWifiEnabled(false);
            }
        }

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

        /**
         * 根据给定的ssid信号量和总级别,判断当前信号量,在什么级别
         *
         * @param rssi
         * @param numLevels
         * @return
         */
        public static int getSignalNumsLevel(int rssi, int numLevels) {
            if (wifiManager == null) {
                return -1;
            }
            return WifiManager.calculateSignalLevel(rssi, numLevels);
        }

        /**
         * 获取ssid的加密方式
         */
        public static WifiCipherType getCipherType(String ssid) {
            if (wifiManager == null) {
                return null;
            }
            List<ScanResult> list = wifiManager.getScanResults();

            for (ScanResult scResult : list) {

                if (!TextUtils.isEmpty(scResult.SSID) && scResult.SSID.equals(ssid)) {
                    String capabilities = scResult.capabilities;
                    if (!TextUtils.isEmpty(capabilities)) {

                        if (capabilities.contains("WPA")
                                || capabilities.contains("wpa")) {
                            Log.e("wifidemo", "wpa");
                            return WifiCipherType.WIFICIPHER_WPA;
                        } else if (capabilities.contains("WEP")
                                || capabilities.contains("wep")) {
                            Log.e("wifidemo", "wep");
                            return WifiCipherType.WIFICIPHER_WEP;
                        } else {
                            Log.e("wifidemo", "no");
                            return WifiCipherType.WIFICIPHER_NOPASS;
                        }
                    }
                }
            }
            return WifiCipherType.WIFICIPHER_INVALID;
        }

        /**
         * 获取 bssid 接入点的地址
         * @return
         */
        public static String getBSSID() {
            if (wifiManager == null) {
                return null;
            }
            WifiInfo info = wifiManager.getConnectionInfo();
            Log.e("wifidemo", "getBSSID" + info.getBSSID());
            if (info == null) {
                return null;
            }
            return info.getBSSID();
        }

        /**
         * 获取网关地址
         *
         * @return
         */
        public static String getGateway() {
            if (wifiManager == null) {
                return "";
            }
            InetAddress inetAddress = NetWorkUtils.intToInetAddress(wifiManager.getDhcpInfo().gateway);
            if (inetAddress == null) {
                return "";
            }
            return inetAddress.getHostAddress();
        }

        /**
         * 获取ip地址
         * @return
         */
        public static String getIpAddress(){
            if (wifiManager == null) {
                return "";
            }
            InetAddress inetAddress = NetWorkUtils.intToInetAddress(wifiManager.getConnectionInfo().getIpAddress());
            if (inetAddress == null) {
                return "";
            }
            return inetAddress.getHostAddress();
        }
        /**
         * 获取mac地址
         * @return
         */
        public static String getMacAddress(){
            if (wifiManager == null) {
                return "";
            }
            return wifiManager.getConnectionInfo().getMacAddress();
        }
        /**
         * 获取wifi名称
         *
         * @return
         */
        public static String getSSID() {
            if (wifiManager == null) {
                return null;
            }
            WifiInfo info = wifiManager.getConnectionInfo();
            String ssid = info.getSSID();
            if (ssid != null) {
                ssid = ssid.substring(1, ssid.length() - 1);
            }
            return ssid;
        }

        /**
         * 扫描WIFI AP
         */
        public static boolean startStan() {
            if (wifiManager == null) {
                return false;
            }
            
            if (!wifiManager.isWifiEnabled()) {
                wifiManager.setWifiEnabled(true);
                
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return wifiManager.startScan();
        }

        /**
         * 获取所有WIFI AP
         */
        public static List<ScanResult> getScanResults() {
            List<ScanResult> srList = wifiManager.getScanResults();
            if (srList == null) {
                srList = new ArrayList<ScanResult>();
            }
            return srList;
        }
}

5、NetWorkUtils

package com.hyc.utils;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

public class NetWorkUtils {

    private static final String IPADDRESS ="172.20.30.197";

    private static final String PINGURL = "172.20.30.197";

    private static final String URL = "http://www.baidu.com";


    public static boolean ping() throws Exception {
        int  timeOut =  3000 ;  //超时应该在3钞以上
        boolean status = InetAddress.getByName(IPADDRESS).isReachable(timeOut);     // 当返回值是true时,说明host是可用的,false则不可。
        return status;
    }

    public static boolean isNetWork(String pingUrl){
        try {
            Process process = Runtime.getRuntime().exec("/system/bin/ping -c 1 -w 100 www.baid.com");
            int status = process.waitFor();
            return status==0;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return false;
    }

    public static boolean isNetWork(){
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            java.net.URL url = new URL(URL);
            // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式:get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间:15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间:60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接,获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封装输入流is,并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
                Log.d("NetWorkUtils", "=== result:" + result);
                return true;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            connection.disconnect();// 关闭远程连接
        }

        return false;
    }

    /**
     * Convert a IPv4 address from an integer to an InetAddress.
     *
     * @param hostAddress
     *            an int corresponding to the IPv4 address in network byte order
     */
    public static InetAddress intToInetAddress(int hostAddress) {
        byte[] addressBytes = { (byte) (0xff & hostAddress), (byte) (0xff & (hostAddress >> 8)),
                (byte) (0xff & (hostAddress >> 16)), (byte) (0xff & (hostAddress >> 24)) };

        try {
            return InetAddress.getByAddress(addressBytes);
        } catch (UnknownHostException e) {
            throw new AssertionError();
        }
    }

    /**
     * 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();
        return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) | ((addr[1] & 0xff) << 8) | (addr[0] & 0xff);
    }


}

 

6、在清单文件中设置wifi权限

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

 7、demo源码:

https://github.com/hongchuanfeng/WifiDemo

posted @ 2019-10-24 11:30  大空白纸  阅读(2716)  评论(1编辑  收藏  举报