嗨,今天给大家带来Android开发wifi模块的功能,包涵检查网络状态,开启Wi-Fi,关闭Wi-Fi,扫描附近Wi-Fi,链接Wi-Fi,…
首先创建两个.xml界面,如下:mbtton.xml ,wifi_listitem.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include layout="@layout/test_gridview_item"/>
LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/check_wifi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="检查"/>
<Button
android:id="@+id/open_wifi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="打开"/>
<Button
android:id="@+id/close_wifi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="关闭"/>
<Button
android:id="@+id/scan_wifi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="扫描"/>
<ListView
android:id="@+id/wifi_list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
ListView>
LinearLayout>
LinearLayout>
wifi_listitem.xml界面:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/ssid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="123"/>
<ImageView
android:id="@+id/wifi_level"
android:layout_width="30dip"
android:layout_height="30dip"
android:background="@mipmap/ic_launcher"
/>
LinearLayout>
LinearLayout>
然后就是建立java,adapter程序(MbuttonActivity.java ,WifiAdmin.java)
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
/**
* Created by rnd on 2018/3/12.
*/
public class MbuttonActivity extends Activity implements View.OnClickListener {
public static final String TAG = "MainActivity";
private Button check_wifi,open_wifi,close_wifi,scan_wifi;
private ListView mlistView;
protected WifiAdmin mWifiAdmin;
private List mWifiList;
public int level;
protected String ssid;
private LinearLayout toolbar;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mbutton);
mWifiAdmin = new WifiAdmin(MbuttonActivity.this);
initViews();
IntentFilter filter = new IntentFilter(
WifiManager.NETWORK_STATE_CHANGED_ACTION);
//="android.net.wifi.STATE_CHANGE" 监听wifi状态的变化
registerReceiver(mReceiver, filter);
mlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view,
int position, long id) {
AlertDialog.Builder alert=new AlertDialog.Builder(MbuttonActivity.this);
ssid=mWifiList.get(position).SSID;
alert.setTitle(ssid);
alert.setMessage("输入密码");
final EditText et_password=new EditText(MbuttonActivity.this);
final SharedPreferences preferences=getSharedPreferences("wifi_password",Context.MODE_PRIVATE);
et_password.setText(preferences.getString(ssid, ""));
alert.setView(et_password);
//alert.setView(view1);
alert.setPositiveButton("连接", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
String pw = et_password.getText().toString();
if(null == pw || pw.length() < 8){
Toast.makeText(MbuttonActivity.this, "密码至少8位", Toast.LENGTH_SHORT).show();
return;
}
SharedPreferences.Editor editor=preferences.edit();
editor.putString(ssid, pw); //保存密码
editor.commit();
mWifiAdmin.addNetwork(mWifiAdmin.CreateWifiInfo(ssid, et_password.getText().toString(), 3));
}
});
alert.setNegativeButton("取消", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
//
//mWifiAdmin.removeWifi(mWifiAdmin.getNetworkId());
}
});
alert.create();
alert.show();
}
});
}
/*
* 控件初始化
* */
private void initViews() {
check_wifi=(Button) findViewById(R.id.check_wifi);
open_wifi=(Button) findViewById(R.id.open_wifi);
close_wifi=(Button) findViewById(R.id.close_wifi);
scan_wifi=(Button) findViewById(R.id.scan_wifi);
mlistView=(ListView) findViewById(R.id.wifi_list);
toolbar=findViewById(R.id.toolbar);
check_wifi.setOnClickListener(MbuttonActivity.this);
open_wifi.setOnClickListener(MbuttonActivity.this);
close_wifi.setOnClickListener(MbuttonActivity.this);
scan_wifi.setOnClickListener(MbuttonActivity.this);
toolbar.setOnClickListener(MbuttonActivity.this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.check_wifi:
mWifiAdmin.checkState(MbuttonActivity.this);
break;
case R.id.open_wifi:
mWifiAdmin.openWifi(MbuttonActivity.this);
break;
case R.id.close_wifi:
mWifiAdmin.closeWifi(MbuttonActivity.this);
break;
case R.id.toolbar:
finish();
break;
case R.id.scan_wifi:
mWifiAdmin.startScan(MbuttonActivity.this);
mWifiList=mWifiAdmin.getWifiList();
if(mWifiList!=null){
mlistView.setAdapter(new MyAdapter(this,mWifiList));
new Utility().setListViewHeightBasedOnChildren(mlistView);
}
break;
default:
break;
}
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
public class MyAdapter extends BaseAdapter{
LayoutInflater inflater;
List list;
public MyAdapter(Context context, List list){
this.inflater=LayoutInflater.from(context);
this.list=list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@SuppressLint({ "ViewHolder", "InflateParams" })
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view=null;
view=inflater.inflate(R.layout.wifi_listitem, null);
ScanResult scanResult = list.get(position);
TextView wifi_ssid=(TextView) view.findViewById(R.id.ssid);
ImageView wifi_level=(ImageView) view.findViewById(R.id.wifi_level);
wifi_ssid.setText(scanResult.SSID);
Log.i(TAG, "scanResult.SSID="+scanResult);
level=WifiManager.calculateSignalLevel(scanResult.level,5);
if(scanResult.capabilities.contains("WEP")||scanResult.capabilities.contains("PSK")||
scanResult.capabilities.contains("EAP")){
wifi_level.setImageResource(R.drawable.btoom_withe);
}else{
wifi_level.setImageResource(R.drawable.btoom_withe);
}
wifi_level.setImageLevel(level);
//判断信号强度,显示对应的指示图标
return view;
}
}
/*设置listview的高度*/
public class Utility {
public void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}
//监听wifi状态
private BroadcastReceiver mReceiver = new BroadcastReceiver (){
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(wifiInfo.isConnected()){
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
String wifiSSID = wifiManager.getConnectionInfo()
.getSSID();
Toast.makeText(context, wifiSSID+"连接成功", 1).show();
}
}
};
}
创建WifiAdmin.java程序入口;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.widget.Toast;
public class WifiAdmin {
// 定义WifiManager对象
private WifiManager mWifiManager;
// 定义WifiInfo对象
private WifiInfo mWifiInfo;
// 扫描出的网络连接列表
private List mWifiList;
// 网络连接列表
private List mWifiConfiguration;
// 定义一个WifiLock
WifiLock mWifiLock;
// 构造器
public WifiAdmin(Context context) {
// 取得WifiManager对象
mWifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
// 取得WifiInfo对象
mWifiInfo = mWifiManager.getConnectionInfo();
}
// 打开WIFI
public void openWifi(Context context) {
if (!mWifiManager.isWifiEnabled()) {
mWifiManager.setWifiEnabled(true);
}else if (mWifiManager.getWifiState() == 2) {
Toast.makeText(context,"亲,Wifi正在开启,不用再开了", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,"亲,Wifi已经开启,不用再开了", Toast.LENGTH_SHORT).show();
}
}
// 关闭WIFI
public void closeWifi(Context context) {
if (mWifiManager.isWifiEnabled()) {
mWifiManager.setWifiEnabled(false);
}else if(mWifiManager.getWifiState() == 1){
Toast.makeText(context,"亲,Wifi已经关闭,不用再关了", Toast.LENGTH_SHORT).show();
}else if (mWifiManager.getWifiState() == 0) {
Toast.makeText(context,"亲,Wifi正在关闭,不用再关了", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,"请重新关闭", Toast.LENGTH_SHORT).show();
}
}
// 检查当前WIFI状态
public void checkState(Context context) {
if (mWifiManager.getWifiState() == 0) {
Toast.makeText(context,"Wifi正在关闭", Toast.LENGTH_SHORT).show();
} else if (mWifiManager.getWifiState() == 1) {
Toast.makeText(context,"Wifi已经关闭", Toast.LENGTH_SHORT).show();
} else if (mWifiManager.getWifiState() == 2) {
Toast.makeText(context,"Wifi正在开启", Toast.LENGTH_SHORT).show();
} else if (mWifiManager.getWifiState() == 3) {
Toast.makeText(context,"Wifi已经开启", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context,"没有获取到WiFi状态", Toast.LENGTH_SHORT).show();
}
}
// 锁定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 getConfiguration() {
return mWifiConfiguration;
}
// 指定配置好的网络进行连接
public void connectConfiguration(int index) {
// 索引大于配置好的网络索引返回
if (index > mWifiConfiguration.size()) {
return;
}
// 连接配置好的指定ID的网络
mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId,
true);
}
public void startScan(Context context) {
mWifiManager.startScan();
//得到扫描结果
List results = mWifiManager.getScanResults();
// 得到配置好的网络连接
mWifiConfiguration = mWifiManager.getConfiguredNetworks();
if (results == null) {
if(mWifiManager.getWifiState()==3){
Toast.makeText(context,"当前区域没有无线网络",Toast.LENGTH_SHORT).show();
}else if(mWifiManager.getWifiState()==2){
Toast.makeText(context,"wifi正在开启,请稍后扫描", Toast.LENGTH_SHORT).show();
}else{Toast.makeText(context,"WiFi没有开启", Toast.LENGTH_SHORT).show();
}
} else {
mWifiList = new ArrayList();
for(ScanResult result : results){
if (result.SSID == null || result.SSID.length() == 0 || result.capabilities.contains("[IBSS]")) {
continue;
}
boolean found = false;
for(ScanResult item:mWifiList){
if(item.SSID.equals(result.SSID)&&item.capabilities.equals(result.capabilities)){
found = true;break;
}
}
if(!found){
mWifiList.add(result);
}
}
}
}
// 得到网络列表
public List 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 void addNetwork(WifiConfiguration wcg) {
int wcgID = mWifiManager.addNetwork(wcg);
boolean b = mWifiManager.enableNetwork(wcgID, true);
System.out.println("a--" + wcgID);
System.out.println("b--" + b);
}
// 断开指定ID的网络
public void disconnectWifi(int netId) {
mWifiManager.disableNetwork(netId);
mWifiManager.disconnect();
}
public void removeWifi(int netId) {
disconnectWifi(netId);
mWifiManager.removeNetwork(netId);
}
//然后是一个实际应用方法,只验证过没有密码的情况:
public WifiConfiguration CreateWifiInfo(String SSID, String Password, int Type)
{
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)
{
List existingConfigs = mWifiManager.getConfiguredNetworks();
for (WifiConfiguration existingConfig : existingConfigs)
{
if (existingConfig.SSID.equals("\""+SSID+"\""))
{
return existingConfig;
}
}
return null;
}
}
把代码都复制上去,就可以看到效果啦,是不是特别的爽,感觉好高端大气牛逼?如果觉得此篇文章对您有所帮助,请别忘记关注或点赞,博主还会继续发表更有趣的文章,有问题可以留言,望各位每天进步一点点,学无止境!!