Java教程

基于安卓9的wifi自动连接和校园网自动连接程序

本文主要是介绍基于安卓9的wifi自动连接和校园网自动连接程序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
实现目的,我校校园网需要先打开wlan在选择连接到指定wifi,然后会弹出一个认证界面,输入账号密码才可登入,于是自然而然的想能不能完成自动处理,做到一键登入,于是写了这个程序。
打开该程序后能自打开wlan,扫描周围的wifi,根据ssid找到要连接的wifi,自动尝试连接,连接后get请求认证页面来认证。
注意安卓10以上无法运行(因为我手机是安卓9,以此来开发的,然后发现这些组件后面被弃用了,因此代码基本也只是自用,账号密码在代码里面写死了)


MainActivity
package com.example.http;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import java.io.IOException;
import java.util.List;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    WifiManager wifiManager;
    List<ScanResult> scanResult;
    List<WifiConfiguration> wifiConfiguration;
    String ip;
    private OkHttpClient okHttpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        okHttpClient = new OkHttpClient();
        connectedWifi(this);

        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        ip = intToIp(ipAddress);

    }



    public void no(View view) {
        new Thread() {
            @Override
            public void run() {
                Request myre = new Request.Builder().url("注销的get url").build();
                Log.e("TEST", "no");
                Call call = okHttpClient.newCall(myre);
                try {
                    Response response = call.execute();
                    Log.e("TEST", response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }


    public void get(View view) {
        new Thread() {
            @Override
            public void run() {
                Request myre = new Request.Builder().url("登入的get url").build();
                Log.e("TEST", "get");
                Call call = okHttpClient.newCall(myre);
                try {
                    Response response = call.execute();
                    Log.e("TEST", response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }


    private void connectedWifi(MainActivity context) {

        String[] permission = new String[]{

                "ACCESS_FINE_LOCATION"

                ,"ACCESS_COARSE_LOCATION"
        };

        Permissions.checkPermission(this , permission);




        wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
        int wifiId;
        openWifi();

        Log.e("TEST","ok");
        while (!wifiManager.isWifiEnabled()) //等待到WiFi开了
        { Log.e("TEST","a");}

        if (wifiManager.isWifiEnabled()) {
            wifiManager.startScan();
            scanResult = wifiManager.getScanResults();

            Log.e("TEST", "扫描出的热点数量:" + String.valueOf(scanResult.size()));

            wifiConfiguration = wifiManager.getConfiguredNetworks();    //得到配置好的网络列表

            if ((wifiId = isConfiguration("\"NTU\"")) == -1) {
                Log.i("Debug", "需要添加配置");
                //加入了密码
                wifiId = addWifiConfig(scanResult, "NTU","");
            } else
                Log.i("Debug", "不需要添加");
            if (wifiId != -1) {
                if(connectWifi(wifiId)){
                    Log.i("Debug","连接成功!");
                }
                else {
                    Log.i("Debug","连接失败!");
                }
            }
        }
        else{
            Log.i("Debug","未打开wifi");
        }
    }

    /**
     * 打开Wifi
     */
    private boolean openWifi() {
        if (!wifiManager.isWifiEnabled()) {
            return wifiManager.setWifiEnabled(true);
        } else if(wifiManager.isWifiEnabled()){
            return true;
        }
        else{
            return false;
        }
    }

    /**
     * 判断是否需要添加配置
     */
    private int isConfiguration(String SSID) {
        for (int i = 0; i < wifiConfiguration.size(); i++) {
            Log.i("Debug", "配置中的wifi列表:"+wifiConfiguration.get(i).SSID);
            Log.e("Debug", String.valueOf(wifiConfiguration.get(i).networkId)+"   "+wifiConfiguration.get(i).SSID);
            if (wifiConfiguration.get(i).SSID.equals(SSID)) {
                return wifiConfiguration.get(i).networkId;
            }
        }
        return -1;
    }



    private boolean connectWifi(int wifiId) {
        Log.e("Debug", String.valueOf(wifiId));
        Log.e("Debug", "添加成功");
        boolean flag;
        Log.i("Debug","wifiConfiguration的数量:"+String.valueOf(wifiConfiguration.size()));
        flag=wifiManager.enableNetwork(wifiId,false);
        Log.e("Debug", String.valueOf(flag));
        return flag;

    }

    /**
     * 添加配置
     */
    private int addWifiConfig(List<ScanResult> scanResult, String ssid,String pass) {
        int wifiId = -1;
        Log.i("Debug", "扫描出的热点数量:"+scanResult.size()+"  需要添加的热点"+ssid);
        for (int i = 0; i < scanResult.size(); i++) {
            ScanResult wifi = scanResult.get(i);
            Log.i("Debug", "扫描出的wifi列表:"+wifi.SSID);
            if (wifi.SSID.equals(ssid)) {
                Log.i("Debug", "准备添加");
                WifiConfiguration wifiConfig = new WifiConfiguration();
                wifiConfig.SSID = "\"" + wifi.SSID + "\"";  //需要用双引号括起来

                //加入了密码
                wifiConfig.hiddenSSID = false;
                wifiConfig.status = WifiConfiguration.  Status.ENABLED;
                wifiConfig.preSharedKey = null;
                wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

                wifiId = wifiManager.addNetwork(wifiConfig);
                Log.e("D1ebug", String.valueOf(wifiId));
                if (wifiId != -1) {
                    Log.e("Debug", "添加成功"+wifiId);
                    return wifiId;
                }
            }
        }
        return wifiId;
    }


    private static class Permissions {
        public static void checkPermission(Activity activity , String[] permission){
            String[] noPermission = new String[permission.length];
            int j = 0 ;
            for (int i = 0; i < permission.length; i++) {
                if (activity.checkSelfPermission(permission[i]) == PackageManager.PERMISSION_DENIED){
                    if (permission[i] != null){
                        requestPermisson(new String[]{permission[i]} ,  activity );
                    }
                }
            }
        }
        private static void requestPermisson(String[] s , Activity activity) {
            ActivityCompat.requestPermissions(activity , s  , 100);
        }
    }

    private String intToIp(int i) {

        return (i & 0xFF ) + "." +
                ((i >> 8 ) & 0xFF) + "." +
                ((i >> 16 ) & 0xFF) + "." +
                ( i >> 24 & 0xFF) ;
    }


}

 

activity_main

<?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=".MainActivity"
    android:orientation="vertical">

    <Button
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="连接"
        android:onClick="get"
        tools:ignore="OnClick"/>

    <Button
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="注销"
        android:onClick="no"
        tools:ignore="OnClick"/>






</LinearLayout>

 

 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.http">

    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <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_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:networkSecurityConfig="@xml/net_sc"
        android:theme="@style/Theme.Http">
        <meta-data
            android:name="com.google.android.actions"
            android:resource="@xml/net_sc" />

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

 

 

 net_sc.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

 

 

核心代码如上,其余的如导入包啥的不赘述了。

注意由于需要扫描wifi需要开启手机定位功能,并且给该程序位置权限。

 

演示视频:https://www.bilibili.com/video/BV1iT4y1Y7KS

  

这篇关于基于安卓9的wifi自动连接和校园网自动连接程序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!