注意:编译sdk版本
minSdk 21
targetSdk 28
亲自测试,在Android10上正常使用
包依赖
implementation 'com.thanosfisherman.elvis:elvis:3.0'
api 'com.thanosfisherman.wifiutils:wifiutils:1.6.2'
2.activity界面
package com.xiaoya.bluetooth.wifi.pages;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.hb.dialog.myDialog.MyAlertInputDialog;
import com.thanosfisherman.wifiutils.WifiUtils;
import com.thanosfisherman.wifiutils.wifiScan.ScanResultsListener;
import com.xiaoya.bluetooth.R;
import com.xiaoya.bluetooth.wifi.adapter.WifiListAdapter;
import com.xiaoya.bluetooth.wifi.bean.WifiBean;
import com.xiaoya.bluetooth.wifi.deal.ConnectionManager;
import com.xiaoya.bluetooth.wifi.deal.LoginDialogUtil;
import com.xiaoya.bluetooth.wifi.utils.HandlerUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class WiFiActivity extends Activity implements HandlerUtils.OnReceiveMessageListener {
//url:https://github.com/ThanosFisherman/WifiUtils.git
// 权限请求码
private static final int PERMISSION_REQUEST_CODE = 0;
// 两个权限需要动态申请
private static final String[] NEEDED_PERMISSIONS = new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
};
private HandlerUtils.HandlerHolder handlerUtils;
//view
private RecyclerView recycleview;
private Switch switchBt;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.oklayout);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 555);
return;
}
// SSID 扫描wifi
// SSID 扫描wifi
// new ConnectionManager(WiFiActivity.this).scanWithWAP();
// 新方法连接wifi
// new ConnectionManager(WiFiActivity.this).connectWifiWithWAP(wifiName3, wifiPassword3);
// 取消正在连接的wifi
// new ConnectionManager(WiFiActivity.this).cancelConnectWithWAP(wifiName3, wifiPassword3);
// 这个bssid是扫描扫出来的,跟ssid对应 ,ssid其实就是wifi名称
// new ConnectionManager(WiFiActivity.this).wpsConnectWithWAP("54:a7:03:dd:9e:96", wifiPassword3);
// 断开连接wifi
// new ConnectionManager(WiFiActivity.this).disConnectWithWAP();
// 不保存且断开链接
// new ConnectionManager(WiFiActivity.this).disConnectDeleteWithWAP(wifiName3);
init();
}
/**
* 判断权限
* 是否通过,
* 如果通过
* 就初始化
*/
private boolean mHasPermission; // 是否通过权限
private void init() {
mHasPermission = checkPermission();
if (!mHasPermission) {
// 未获取权限,申请权限
requestPermission();
Toast.makeText(WiFiActivity.this, "未获取权限,申请权限", Toast.LENGTH_SHORT).show();
} else if (mHasPermission) {
// 已经获取权限
Toast.makeText(WiFiActivity.this, "已经获取权限", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(WiFiActivity.this, "WIFI处于关闭状态", Toast.LENGTH_SHORT).show();
}
}
/**
* 申请
* 权限
*/
private void requestPermission() {
ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, PERMISSION_REQUEST_CODE);
}
/**
* @return 检查
* 是否
* 已经
* 授予权限
*/
private boolean checkPermission() {
for (String permission : NEEDED_PERMISSIONS) {
if (ActivityCompat.checkSelfPermission(this, permission)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
@Override
protected void onResume() {
super.onResume();
initView();
}
/**
* 初始化
* view
*/
private List mList = new ArrayList<>();
private HandlerUtils.HandlerHolder myHandler;
private static final int MSG_WIFI_TAG = 0x11111;//连接WiFi成功
private static final int MSG_WIFI_TWO = 0x11112;//消息标记
private WifiListAdapter wifiListAdapter;
private WifiManager wifiMgr;//wifi管理
private void initView() {
handlerUtils = new HandlerUtils.HandlerHolder(this);
recycleview = findViewById(R.id.recycleview);
switchBt = findViewById(R.id.switch_bt);
LinearLayoutManager managerVertical = new LinearLayoutManager(WiFiActivity.this);
managerVertical.setOrientation(LinearLayoutManager.VERTICAL);
recycleview.setLayoutManager(managerVertical);
recycleview.setHasFixedSize(true);
//选择
switchBt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d("TAG", "=====isChecked======" + isChecked);
Toast.makeText(WiFiActivity.this, "开始扫描0000", Toast.LENGTH_LONG).show();
if (isChecked) {//打开WiFi
LoginDialogUtil.getInstance().showLoadingDialog(WiFiActivity.this, "Wifi扫描中...");
Toast.makeText(WiFiActivity.this, "开始扫描", Toast.LENGTH_LONG).show();
switchBt.setSwitchPadding(2);
openWifi();
} else { //关闭wifi
Toast.makeText(WiFiActivity.this, "关闭扫描", Toast.LENGTH_LONG).show();
switchBt.setSwitchPadding(1);
new ConnectionManager(WiFiActivity.this).closeWithWAP();
mList.clear();
wifiListAdapter.notifyDataSetChanged();
}
}
});
wifiListAdapter = new WifiListAdapter(this, mList);
recycleview.setAdapter(wifiListAdapter);
wifiMgr = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//接口回调
wifiListAdapter.setMyOnItemClickListener(new WifiListAdapter.OnItemClickListener() {
@Override
public void OnItemClick(View view, int position) {
//连接wifi
Log.d("TAG", "====position=====" + mList.get(position).getWifiName());
final MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(WiFiActivity.this).builder()
.setTitle("请输入wifi" + mList.get(position).getWifiName() + "密码")
.setEditText("");
myAlertInputDialog.setPositiveButton("确认", new View.OnClickListener() {
@Override
public void onClick(View v) {
LoginDialogUtil.getInstance().showLoadingDialog(WiFiActivity.this, "Wifi连接中...");//开启加载动画
Log.d("TAG", "===请输入wifi===" +
mList.get(position).getWifiName() +
"======" + myAlertInputDialog
.getContentEditText()
.getText()
.toString().trim());
wifiUserName = mList.get(position).getWifiName().trim();
wifiPassWord = myAlertInputDialog
.getContentEditText()
.getText()
.toString().trim();
handlerUtils.sendEmptyMessageDelayed(MSG_WIFI_TAG, 100);
myAlertInputDialog.dismiss();
}
}).setNegativeButton("取消", new View.OnClickListener() {
@Override
public void onClick(View v) {
myAlertInputDialog.dismiss();
}
});
myAlertInputDialog.show();
}
@Override
public void OnItemLonClick(int position) {
}
});
}
/**
* 打开
* 网络
*/
private void openWifi() {
new ConnectionManager(WiFiActivity.this).openWithWAP();
new Thread(new Runnable() {
@Override
public void run() {
try {
Looper.prepare();
Thread.sleep(1000);
scanWithWAP();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
/**
* 扫描
* wifi
*/
public void scanWithWAP() {
WifiUtils.withContext(this).scanWifi(new ScanResultsListener() {
@Override
public void onScanResults(@NonNull List scanResults) {
mList.clear();
for (int i = 0; i < scanResults.size(); i++) {
//SSID:wifi名字
//加密方式:capabilities
//信号强度:level
if (!scanResults.get(i).SSID.isEmpty() && scanResults.get(i).SSID != "") {
WifiBean wifiBean = new WifiBean();
wifiBean.setWifiName(scanResults.get(i).SSID);
wifiBean.setState("未连接");
wifiBean.setBsssiD(scanResults.get(i).BSSID);
wifiBean.setCapabilities(scanResults.get(i).capabilities);
wifiBean.setLevel(scanResults.get(i).level);
mList.add(wifiBean);
}
Log.d("TAG", "====扫码结果====" +
scanResults.get(i).SSID + "====" +
scanResults.get(i).BSSID + "===" +
scanResults.get(i).level + "===" +
scanResults.get(i).capabilities + "==="
);
}
Set userSet = new HashSet<>(mList);
mList.clear();
List mist = new ArrayList<>(userSet);
Log.d("TAG", "======1111=====" + mist.size());
mList.addAll(mist);
Log.d("TAG", "======2222=====" + mList.size());
Collections.sort(mList);
handlerUtils.sendEmptyMessage(MSG_WIFI_TWO);
}
}).start();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public void handlerMessage(Message msg) {
switch (msg.what) {
case MSG_WIFI_TAG:
if (WifiUtils.withContext(WiFiActivity.this).isWifiConnected()) {
Toast.makeText(WiFiActivity.this, "wifi连接成功", Toast.LENGTH_LONG).show();
LoginDialogUtil.getInstance().closeLoadingDialog();//关闭对话框
} else {
handlerUtils.sendEmptyMessageDelayed(MSG_WIFI_TAG, 3000);
connectWiFi(wifiUserName, wifiPassWord);
}
break;
case MSG_WIFI_TWO:
Log.d("TAG", "======刷新数=====" + mList.size());
wifiListAdapter.setVerticalDataList(mList);
LoginDialogUtil.getInstance().closeLoadingDialog();//关闭动画
break;
default:
break;
}
}
/**
* 连接
* WiFi
*/
private String wifiUserName = "";
private String wifiPassWord = "";
private void connectWiFi(String name, String passWord) {
WifiConfiguration wifiCong = new WifiConfiguration();
wifiCong.SSID = "\"" + name.trim() + "\"";//\"转义字符,代表"
wifiCong.preSharedKey = "\"" + passWord.trim() + "\"";//WPA-PSK密码
wifiCong.hiddenSSID = false;
wifiCong.status = WifiConfiguration.Status.ENABLED;
int resstate = wifiMgr.addNetwork(wifiCong);//107将配置好的特定WIFI密码信息添加,添加完成后默认是不激活状态,成功返回ID,否则为-1
Log.d("TAG", "====WIFI密码信息添加状态=====" + resstate);
if (resstate == -1) {
Log.d("TAG", "===再添加一次===WIFI密码信息添加状态===" + resstate);
wifiMgr.addNetwork(wifiCong);
} else {
//wifi连接成功
}
}
}
wifi管理工具
package com.xiaoya.bluetooth.wifi.deal;
import android.content.Context;
import android.net.wifi.ScanResult;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.thanosfisherman.wifiutils.WifiConnectorBuilder;
import com.thanosfisherman.wifiutils.WifiUtils;
import com.thanosfisherman.wifiutils.wifiConnect.ConnectionErrorCode;
import com.thanosfisherman.wifiutils.wifiConnect.ConnectionSuccessListener;
import com.thanosfisherman.wifiutils.wifiDisconnect.DisconnectionErrorCode;
import com.thanosfisherman.wifiutils.wifiDisconnect.DisconnectionSuccessListener;
import com.thanosfisherman.wifiutils.wifiRemove.RemoveErrorCode;
import com.thanosfisherman.wifiutils.wifiRemove.RemoveSuccessListener;
import com.thanosfisherman.wifiutils.wifiScan.ScanResultsListener;
import com.thanosfisherman.wifiutils.wifiWps.ConnectionWpsListener;
import java.util.List;
public class ConnectionManager {
private Context context;
public ConnectionManager(Context context) {
this.context = context;
}
//打开wifi
public void openWithWAP() {
WifiUtils.withContext(context).enableWifi(this::checkResult);
}
//关闭wifi
public void closeWithWAP() {
WifiUtils.withContext(context).disableWifi();
}
//扫描wifi
public void scanWithWAP() {
WifiUtils.withContext(context).scanWifi(new ScanResultsListener() {
@Override
public void onScanResults(@NonNull List scanResults) {
for (int i = 0; i < scanResults.size(); i++) {
//SSID:wifi名字
//加密方式:capabilities
//信号强度:level
Log.d("TAG", "====扫码结果====" +
scanResults.get(i).SSID + "====" +
scanResults.get(i).BSSID + "===" +
scanResults.get(i).level + "===" +
scanResults.get(i).capabilities);
}
}
}).start();
}
//连接wifi
public void connectWifiWithWAP(String name, String password) {
WifiUtils.withContext(context)
.connectWith(name, password)
.setTimeout(20000)
.onConnectionResult(new ConnectionSuccessListener() {
@Override
public void success() {
Log.d("TAG","========连接wifi成功==SUCCESS!======");
Toast.makeText(context, "===连接wifi成功==SUCCESS!", Toast.LENGTH_SHORT).show();
}
@Override
public void failed(@NonNull ConnectionErrorCode errorCode) {
Log.d("TAG","========连接wifi失败==FAIL!======"+errorCode.toString());
Toast.makeText(context, "===连接wifi失败==EPIC FAIL!" + errorCode.toString(), Toast.LENGTH_LONG).show();
}
})
.start();
}
//取消正在连接的wifi
public void cancelConnectWithWAP(String name, String password) {
WifiConnectorBuilder.WifiUtilsBuilder builder = WifiUtils.withContext(context);
builder.connectWith(name, password)
.onConnectionResult(new ConnectionSuccessListener() {
@Override
public void success() {
Toast.makeText(context, "取消 SUCCESS!", Toast.LENGTH_SHORT).show();
}
@Override
public void failed(@NonNull ConnectionErrorCode errorCode) {
Toast.makeText(context, "EPIC FAIL!" + errorCode.toString(), Toast.LENGTH_SHORT).show();
}
})
.start();
builder.cancelAutoConnect();
}
//wps连接wifi
public void wpsConnectWithWAP(String name, String password) {
WifiUtils.withContext(context)
.connectWithWps(name, password)
.onConnectionWpsResult(new ConnectionWpsListener() {
@Override
public void isSuccessful(boolean isSuccess) {
Toast.makeText(context, "" + isSuccess, Toast.LENGTH_SHORT).show();
}
})
.start();
}
//断开wifi
public void disConnectWithWAP() {
WifiUtils.withContext(context)
.disconnect(new DisconnectionSuccessListener() {
@Override
public void success() {
Toast.makeText(context, "Disconnect success!", Toast.LENGTH_SHORT).show();
}
@Override
public void failed(@NonNull DisconnectionErrorCode errorCode) {
Toast.makeText(context, "Failed to disconnect: " + errorCode.toString(), Toast.LENGTH_SHORT).show();
}
});
}
//断开连接并删除保存的网络配置 wifi
public void disConnectDeleteWithWAP(String nameSsid) {
WifiUtils.withContext(context)
.remove(nameSsid, new RemoveSuccessListener() {
@Override
public void success() {
Toast.makeText(context, "Remove success!", Toast.LENGTH_SHORT).show();
}
@Override
public void failed(@NonNull RemoveErrorCode errorCode) {
Toast.makeText(context, "Failed to disconnect and remove: $errorCode", Toast.LENGTH_SHORT).show();
}
});
}
private void getScanResults(@NonNull final List results) {
if (results.isEmpty()) {
Log.e("TAG", "SCAN RESULTS IT'S EMPTY");
return;
}
Log.e("TAG", "GOT SCAN RESULTS " + results);
}
private void checkResult(boolean isSuccess) {
if (isSuccess)
Toast.makeText(context, "WIFI已经打开", Toast.LENGTH_SHORT).show();
else
Toast.makeText(context, "无法打开wifi", Toast.LENGTH_SHORT).show();
}
}
效果
详情见代码
资源下载
https://download.csdn.net/download/shi450561200/87368299