代码实现WIFI自动连接与连接指定WIFI源码

2022-02-22 13:55:17 浏览数 (1)

最近家里老人总是问我如何连接WIFI,和他们电话讲又讲不清楚,于是我想到了写一个,打开自动连接指定WIFI的软件。练练手。

废话不多说,首先布局,简单!

两个文本框一个按钮

代码语言:javascript复制
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Shezhi"
    android:orientation="vertical"
    android:background="#b2cbfd"
    android:focusable="true"
    android:focusableInTouchMode="true">
<EditText
    android:hint="请输入wifi名"
    android:layout_marginTop="10dp"
    android:id="@ id/mingzi"
    android:layout_width="match_parent"
    android:layout_height="50dp" />
    <EditText
        android:hint="请输入wifi密码"
        android:layout_marginTop="10dp"
        android:id="@ id/mima"
        android:layout_width="match_parent"
        android:layout_height="50dp" />
    <Button
        android:textSize="20sp"
        android:text="确定"
        android:id="@ id/queding"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

设置连接WIFI名和密码 将用户输入的WIFI名和密码保存到sp中

代码语言:javascript复制
public class Shezhi extends AppCompatActivity {
        private EditText mingzi;
        private EditText mima;
        private SharedPreferences sharedPreferences;
        private Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shezhi);
        chushihua();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String trim = mingzi.getText().toString().trim();
                String trim1 = mima.getText().toString().trim();
                if (!trim.isEmpty() && !trim1.isEmpty()){
                    SharedPreferences.Editor edit = sharedPreferences.edit();
                    edit.putString("mingzi",trim);
                    edit.putString("mima",trim1);
                    edit.commit();
                    Toast.makeText(getApplicationContext(),"设置成功",Toast.LENGTH_SHORT).show();
                    finish();
                }else {
                    Toast.makeText(getApplicationContext(),"不能为空",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void chushihua() {
        mingzi=(EditText)findViewById(R.id.mingzi);
        mima=(EditText)findViewById(R.id.mima);
        button=(Button)findViewById(R.id.queding);
        sharedPreferences=getSharedPreferences("wifi",0);
    }
}

WIFI连接工具类 这是一个封装好的类(用于连接WIFI的一系列操作),具体里面注释了

代码语言:javascript复制
public class Wifigongju {
    // 定义WifiManager对象
    private WifiManager mWifiManager;
    // 定义WifiInfo对象
    private WifiInfo mWifiInfo;
    // 扫描出的网络连接列表
    private List<ScanResult> mWifiList;
    // 网络连接列表
    private List<WifiConfiguration> mWifiConfiguration;
    // 定义一个WifiLock
    WifiManager.WifiLock mWifiLock;


    // 构造器
    public Wifigongju(Context context) {

        // 取得WifiManager对象
        mWifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);

        // 取得WifiInfo对象
        mWifiInfo = mWifiManager.getConnectionInfo();
    }

    // 打开WIFI
    public void openWifi() {
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(true);
        }else {
            return;
        }

    }

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

    // 检查当前WIFI状态
    public int checkState() {
        return mWifiManager.getWifiState();
    }

    // 锁定WifiLock
    public void acquireWifiLock() {
        mWifiLock.acquire();
    }

    // 解锁WifiLock
    public void releaseWifiLock() {
        // 判断时候锁定
        if (mWifiLock.isHeld()) {
            mWifiLock.acquire();
        }
    }

    // 创建一个WifiLock
    public void creatWifiLock() {
        mWifiLock = mWifiManager.createWifiLock("Test");
    }

    // 得到配置好的网络
    public List<WifiConfiguration> getConfiguration() {
        return mWifiConfiguration;

    }

    // 指定配置好的网络进行连接
    public void connectConfiguration(int index) {
        // 索引大于配置好的网络索引返回
        if (index > mWifiConfiguration.size()) {
            return;
        }
        // 连接配置好的指定ID的网络
        mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId,
                true);
    }

    public void startScan() {
        mWifiManager.startScan();
        // 得到扫描结果
        mWifiList = mWifiManager.getScanResults();
        // 得到配置好的网络连接
        mWifiConfiguration = mWifiManager.getConfiguredNetworks();
    }

    // 得到网络列表
    public List<ScanResult> getWifiList() {
        return mWifiList;
    }

    // 查看扫描结果
    public StringBuilder lookUpScan() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < mWifiList.size(); i  ) {
            stringBuilder
                    .append("Index_"   new Integer(i   1).toString()   ":");
            // 将ScanResult信息转换成一个字符串包
            // 其中把包括:BSSID、SSID、capabilities、frequency、level
            stringBuilder.append((mWifiList.get(i)).toString());
            stringBuilder.append("/n");
        }
        return stringBuilder;
    }

    // 得到MAC地址
    public String getMacAddress() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
    }

    // 得到接入点的BSSID
    public String getBSSID() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
    }

    // 得到IP地址
    public int getIPAddress() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
    }

    // 得到连接的ID
    public int getNetworkId() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
    }

    // 得到WifiInfo的所有信息包
    public String getWifiInfo() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
    }

    // 添加一个网络并连接
    public boolean addNetwork(WifiConfiguration wcg) {


        int wcgID = mWifiManager.addNetwork(wcg);
        boolean b =  mWifiManager.enableNetwork(wcgID, true);
        Log.e("连接状态", String.valueOf(b));
        return b;
    }

    // 断开指定ID的网络
    public void disconnectWifi(int netId) {
        mWifiManager.disableNetwork(netId);
        mWifiManager.disconnect();
    }


//然后是一个实际应用方法,只验证过没有密码的情况:

    public WifiConfiguration CreateWifiInfo(String SSID, String Password, int Type)
                
    {
//        while (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING){
//
//            try {
//                Thread.currentThread();
//                Thread.sleep(100);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }


        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) {
                mWifiManager.removeNetwork(tempConfig.networkId);
            }

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

    private WifiConfiguration IsExsits(String SSID)
    {
        while (mWifiManager.getConfiguredNetworks()==null){

            try {
                Thread.currentThread();
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
            for (WifiConfiguration existingConfig : existingConfigs) {
                if (existingConfig.SSID.equals("""   SSID   """)) {
                    return existingConfig;
                }
            }

        return null;
    }
}

这个类是通用的只要连接WIFI就可以使用这个工具类

由于连接WIFI需要权限,所以我们需要授权

授权(z这是一个封装好的回调接口)动态授权

代码语言:javascript复制
public class BaseActivity extends AppCompatActivity {
    public interface PermissionListener {

        void onGranted();//已授权

        void onDenied(List<String> deniedPermission);//未授权

    }

    private PermissionListener mListener;
    private static final int PERMISSION_REQUESTCODE = 100;

    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);

    }

    public void requestRunPermisssion(String[] permissions, PermissionListener listener){
        mListener = listener;
        List<String> permissionLists = new ArrayList<>();
        for(String permission : permissions){
            if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
                permissionLists.add(permission);
            }
        }

        if(!permissionLists.isEmpty()){
            ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), PERMISSION_REQUESTCODE);
        }else{
            //表示全都授权了
            mListener.onGranted();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case PERMISSION_REQUESTCODE:
                if(grantResults.length > 0){
                    //存放没授权的权限
                    List<String> deniedPermissions = new ArrayList<>();
                    for(int i = 0; i < grantResults.length; i  ){
                        int grantResult = grantResults[i];
                        String permission = permissions[i];
                        if(grantResult != PackageManager.PERMISSION_GRANTED){
                            deniedPermissions.add(permission);
                        }
                    }
                    if(deniedPermissions.isEmpty()){
                        //说明都授权了
                        mListener.onGranted();
                    }else{
                        mListener.onDenied(deniedPermissions);
                    }
                }
                break;
            default:
                break;
        }
    }
}

接下来我们只需要在Main中使用

代码语言:javascript复制
public class MainActivity extends BaseActivity {
    private Button button;
    private SharedPreferences sharedPreferences;
    private TextView shuju;
    private TextView jieguo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        chushihua();
        sharedPreferences = getSharedPreferences("wifi", 0);
        dongtaishouquan();


    }


    private void dongtaishouquan() {
        requestRunPermisssion(new String[]{Manifest.permission.CHANGE_NETWORK_STATE, Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.ACCESS_FINE_LOCATION}, new PermissionListener() {
            @Override
            public void onGranted() {
                if (sharedPreferences.getString("mingzi", "sss").equals("sss") && sharedPreferences.getString("mima", "0").equals("0")) {
                    shuju.setText("失败原因没有设置wifi,请点击下方按钮设置要连接的wifi");
                } else {
                    Wifigongju wifigongju = new Wifigongju(getApplicationContext());
                    wifigongju.openWifi();

                    boolean b = wifigongju.addNetwork(wifigongju.CreateWifiInfo(sharedPreferences.getString("mingzi", "sss"), sharedPreferences.getString("mima", "0"), 3));
                    if (b) {
                        jieguo.setText("连接成功");
                        shuju.setText("已连接至"   wifigongju.getBSSID());
                    } else {
                        jieguo.setText("连接失败");
                    }
                }
            }
            @Override
            public void onDenied(List<String> deniedPermission) {

            }
        });

    }
        private void chushihua () {
            button = (Button) findViewById(R.id.shezhi);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(getApplicationContext(), Shezhi.class));
                }
            });
            shuju = (TextView) findViewById(R.id.shuju);
            jieguo = (TextView) findViewById(R.id.jieguo);
        }

    }

最后权限说明 (重要)

代码语言:javascript复制
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<!-- //修改网络状态权限 -->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<!-- 修改wifi状态的权限 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- //访问网络权限 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- //访问wifi权限 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- 定位权限 -->

这些权限最好都加上,防止app炸!

学习永无止境!加油。

0 人点赞