写一个Android wifi开发程序,适配android11,包括wifi打开、关闭、扫描、连接、断开
时间: 2023-05-28 22:02:20 浏览: 236
以下是一份简单的Android wifi开发程序,适配android 11,包括wifi打开、关闭、扫描、连接和断开。
Java代码:
```java
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@RequiresApi(30)
public class MainActivity extends AppCompatActivity {
private final int REQUEST_CODE_LOCATION_PERMISSION = 100;
private final int REQUEST_CODE_WIFI_PERMISSION = 101;
private WifiManager wifiManager;
private boolean isWifiEnabled;
private WifiScanReceiver wifiScanReceiver;
private List<WifiConfiguration> wifiConfigurations;
private List<WifiInfo> wifiInfos;
private List<ScanResult> scanResults;
private boolean isConnected;
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
isWifiEnabled = wifiManager.isWifiEnabled();
wifiScanReceiver = new WifiScanReceiver();
wifiConfigurations = wifiManager.getConfiguredNetworks();
wifiInfos = new ArrayList<>();
scanResults = new ArrayList<>();
isConnected = false;
handler = new Handler(Looper.getMainLooper());
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_LOCATION_PERMISSION);
} else {
enableWifi();
}
}
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(wifiScanReceiver, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(wifiScanReceiver);
}
@Override
protected void onDestroy() {
super.onDestroy();
disconnect();
disableWifi();
}
private void enableWifi() {
if (!isWifiEnabled) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CHANGE_WIFI_STATE}, REQUEST_CODE_WIFI_PERMISSION);
} else {
wifiManager.setWifiEnabled(true);
isWifiEnabled = true;
Toast.makeText(this, "开启Wifi", Toast.LENGTH_SHORT).show();
}
}
}
private void disableWifi() {
if (isWifiEnabled) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CHANGE_WIFI_STATE}, REQUEST_CODE_WIFI_PERMISSION);
} else {
wifiManager.setWifiEnabled(false);
isWifiEnabled = false;
Toast.makeText(this, "关闭Wifi", Toast.LENGTH_SHORT).show();
}
}
}
private void scanWifi() {
if (isWifiEnabled) {
wifiManager.startScan();
Toast.makeText(this, "开始扫描Wifi", Toast.LENGTH_SHORT).show();
}
}
private void connect(WifiConfiguration wifiConfiguration) {
if (isWifiEnabled) {
int networkId = wifiManager.addNetwork(wifiConfiguration);
if (networkId != -1) {
wifiManager.saveConfiguration();
wifiManager.disconnect();
wifiManager.enableNetwork(networkId, true);
wifiManager.reconnect();
isConnected = true;
Toast.makeText(this, "已连接Wifi", Toast.LENGTH_SHORT).show();
} else {
isConnected = false;
Toast.makeText(this, "连接Wifi失败", Toast.LENGTH_SHORT).show();
}
}
}
private void disconnect() {
if (isWifiEnabled && isConnected) {
wifiManager.disconnect();
isConnected = false;
Toast.makeText(this, "已断开Wifi连接", Toast.LENGTH_SHORT).show();
}
}
private void requestLocationPermission() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_LOCATION_PERMISSION);
}
private void requestWifiPermission() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CHANGE_WIFI_STATE}, REQUEST_CODE_WIFI_PERMISSION);
}
// 单独提取出请求权限的onRequestPermissionsResult方法,后续修改方便
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE_LOCATION_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
enableWifi();
} else {
Toast.makeText(this, "请求位置权限失败,无法开启Wifi", Toast.LENGTH_SHORT).show();
}
}
if (requestCode == REQUEST_CODE_WIFI_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (isWifiEnabled) {
disableWifi();
} else {
enableWifi();
}
} else {
Toast.makeText(this, "请求Wifi权限失败", Toast.LENGTH_SHORT).show();
}
}
}
// Broadcast Receiver
private class WifiScanReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
scanResults = wifiManager.getScanResults();
sortScanResultsByLevel();
Toast.makeText(context, "扫描结束,共找到" + scanResults.size() + "个Wifi", Toast.LENGTH_SHORT).show();
}
}
}
// 排序
private void sortScanResultsByLevel() {
Collections.sort(scanResults, new Comparator<ScanResult>() {
@Override
public int compare(ScanResult o1, ScanResult o2) {
return o2.level - o1.level;
}
});
}
// 获取连接状态
private boolean getConnectivityStatus() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
}
```
阅读全文