<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context="com.example.wifi.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开启wifi"
android:onClick="click1"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="获取扫描信息"
android:onClick="click2"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="获取已经配置过的信息"
android:onClick="click3"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/lv">
</ListView>
</LinearLayout>
package com.example.wifi;
import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static android.R.layout.simple_list_item_1;
public class MainActivity extends AppCompatActivity {
WifiManager wifiManager;
ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 找到ListView控件
lv = (ListView) findViewById(R.id.lv);
// 获取WifiManager实例(要用全局上下文去获取系统wifi服务)
wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// 拿到我当前选的wifi的信息
final ScanResult scanResult = scanResults.get(position);
// 设置一个自定义的密码输入对话框
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("连接wifi");
// 创建文本输入控件
final EditText et = new EditText(MainActivity.this);
et.setHint("请输入密码");
// 把控件设置到对话框里
builder.setView(et);
// 给对话框设置取消按钮监听
builder.setNegativeButton("取消",null);
// 给对话框设置确定按钮监听
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 创建wifi的配置实例
WifiConfiguration config = new WifiConfiguration();
// 获取用户输入的密码
String password = et.getText().toString();
config.SSID = "\"" + scanResult.SSID + "\"";
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;
int networkId = wifiManager.addNetwork(config);
wifiManager.enableNetwork(networkId, true);
}
}).create().show();
}
});
}
// 开启wifi的按钮监听
public void click1(View view){
// WifiManager可以直接操作wifi
// 这里要添加wifi改变状态的权限<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
wifiManager.setWifiEnabled(true);
}
// 获取扫描信息按钮的监听
public void click2(View view){
// 获取所有扫描的热点信息,先确定权限,android6.0(API 23)及以上系统就需要动态添加地理位置的权限,否则不需要
if (Build.VERSION.SDK_INT > 23) {
// 添加地理位置的权限
int check = checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
// 判断是否已经有权限
if (check == PackageManager.PERMISSION_GRANTED) {
// 直接执行扫描代码
getScanResult();
}else{
// 请求用户手动打开权限(String数组是有可能需要打开多个权限,requestCode有可能多个地方需要请求权限)
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},20);
}
}else{
// 有权限就执行,或者低于6.0
getScanResult();
}
}
// 重写onRequestPermissionsResult方法来确定用户是否选择允许权限
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// 回调判断用户点击的是允许还是拒绝
if (requestCode == 20 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
// 允许执行扫描
getScanResult();
}else{
// 拒绝就重新获取或者退出程序(这里就Toast下)
Toast.makeText(this, "没有请求到权限,无法访问wifi", Toast.LENGTH_SHORT).show();
}
}
List<ScanResult> scanResults;
private void getScanResult(){
// wifi管理者调用获取扫描的方法,同时也需要添加ACCESS_WIFI_STATE权限
scanResults = wifiManager.getScanResults();
// 创建一个集合装扫描出的数据
List<String> list = new ArrayList<>();
// 用foreach方法把数据添加到集合里
for (ScanResult scanResult:scanResults) {
// 添加wifi的名称 MAC地址 加密方式 wifi的水平(信号强度)
list.add(scanResult.SSID+"\n"+scanResult.BSSID+"\n"+scanResult.capabilities+"\n"+scanResult.level);
/* // 添加wifi的名称
list.add(scanResult.SSID);
// 添加wifi的MAC地址
list.add(scanResult.BSSID);
// 添加wifi的加密方式
list.add(scanResult.capabilities);
// 添加wifi的水平(信号强度)
list.add(String.valueOf(scanResult.level));*/
}
Log.e("TAG", "-------------"+list.toString());
// 创建一个适配器
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, simple_list_item_1,list);
// ListView设置适配器
lv.setAdapter(adapter);
}
String item;
// 获取已经配置过的信息按钮的监听
public void click3(View view){
List<WifiConfiguration> configuradNetworks = wifiManager.getConfiguredNetworks();
final List<String> list = new ArrayList<>();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("连接过的wifi");
final ListView listView = new ListView(this);
builder.setView(listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv = (TextView)view;
item = (String) tv.getText();
}
});
for (WifiConfiguration configuradNetwork : configuradNetworks) {
list.add("名称:"+configuradNetwork.SSID+"\nID:"+configuradNetwork.networkId+"\n"+configuradNetwork.FQDN);
}
builder.setNegativeButton("取消",null);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "选择了"+ item, Toast.LENGTH_SHORT).show();
}
}).create().show();
}
}
要记得加权限
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />