android 连接wifi案例
1、xml布局文件:
<FrameLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.helloword.WifiTestActivity" > <LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="10dp"
android:orientation="vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp"> <LinearLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:orientation="vertical"> <TextView
android:id="@+id/wifi_state"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:hint="wifi state"
android:textColor="@android:color/black" /> <TextView
android:id="@+id/wifi_name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:hint="wifi name"
android:textColor="@android:color/black" /> <TextView
android:id="@+id/wifi_mac"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:hint="mac"
android:textColor="@android:color/black" /> <TextView
android:id="@+id/ip_address"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:hint="ip address"
android:textColor="@android:color/black" />
<TextView
android:id="@+id/ip_gateway"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:hint="gateway"
android:textColor="@android:color/black" /> <EditText
android:id="@+id/et_pwd"
android:layout_width="360dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:hint="wifi密码" />
</LinearLayout>
<ImageView
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="@android:color/black" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"> <Button
android:id="@+id/search_wifi"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="search wifi" /> <Button
android:id="@+id/connect_wifi"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="connect" /> </LinearLayout> <ListView
android:id="@+id/list_wifi"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"></ListView>
</LinearLayout> <FrameLayout
android:id="@+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone"> <ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout> </FrameLayout>
2、适配xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:textColor="@android:color/black"
android:text="test"
android:id="@+id/wifi_item_name"
android:layout_margin="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
3、activity
package com.example.helloword; import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit; import com.example.helloword.service.TimerService;
import com.example.helloword.service.WifiTimerService;
import com.example.helloword.utils.WifiAutoConnectManager; import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
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.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast; public class WifiTestActivity extends Activity implements View.OnClickListener { EditText et_pwd;
TextView mWifiState;//wifi状态
TextView mWifiName;//Wi-Fi名称
TextView mMac;//物理地址
TextView mIP;//ip地址
TextView mGateway;//网关地址
ListView mListWifi;//Wi-Fi列表
Button mBtnSearch;//搜索Wi-Fi
Button mBtnConnect;//连接Wi-Fi
WifiListAdapter mWifiListAdapter;
public static final int WIFI_SCAN_PERMISSION_CODE = 2;
WorkAsyncTask mWorkAsyncTask = null;
ConnectAsyncTask mConnectAsyncTask = null;
List<ScanResult> mScanResultList = new ArrayList<ScanResult>();
public static String ssid = "";
WifiAutoConnectManager.WifiCipherType type = WifiAutoConnectManager.WifiCipherType.WIFICIPHER_NOPASS;
public static String password = "";//"hyc888888";
FrameLayout progressbar;
boolean isLinked = false; String gateway = "";
String mac = ""; /**
* 处理信号量改变或者扫描结果改变的广播
*/
private BroadcastReceiver mWifiSearchBroadcastReceiver;
private IntentFilter mWifiSearchIntentFilter;
private BroadcastReceiver mWifiConnectBroadcastReceiver;
private IntentFilter mWifiConnectIntentFilter;
private WifiAutoConnectManager mWifiAutoConnectManager; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi_test); Intent intent = new Intent(WifiTestActivity.this, WifiTimerService.class);
//使用Intent传值
intent.putExtra("key","value");
startService(intent); intiView(); //初始化wifi工具
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
mWifiAutoConnectManager = WifiAutoConnectManager.newInstance(wifiManager); // if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// // 获取wifi连接需要定位权限,没有获取权限
// ActivityCompat.requestPermissions(this, new String[]{
// Manifest.permission.ACCESS_COARSE_LOCATION,
// }, WIFI_SCAN_PERMISSION_CODE);
// return;
// } //设置监听wifi状态变化广播
initWifiSate();
} @Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.search_wifi:
if (mWorkAsyncTask != null) {
mWorkAsyncTask.cancel(true);
mWorkAsyncTask = null;
}
mWorkAsyncTask = new WorkAsyncTask();
mWorkAsyncTask.execute();
break;
case R.id.connect_wifi:
if (ssid.equals(WifiAutoConnectManager.getSSID())) {
return;
}
String pwdString = et_pwd.getText().toString().trim();
if(TextUtils.isEmpty(pwdString)){
Toast.makeText(WifiTestActivity.this, "请先填写wifi密码", Toast.LENGTH_SHORT).show();
return;
} password = pwdString; if (mConnectAsyncTask != null) {
mConnectAsyncTask.cancel(true);
mConnectAsyncTask = null;
}
mConnectAsyncTask = new ConnectAsyncTask(ssid, password, type);
mConnectAsyncTask.execute();
break;
default:
break;
} } @Override
protected void onResume() {
super.onResume();
registerReceiver(mWifiSearchBroadcastReceiver, mWifiSearchIntentFilter);
registerReceiver(mWifiConnectBroadcastReceiver, mWifiConnectIntentFilter);
} @Override
protected void onPause() {
super.onPause();
unregisterReceiver(mWifiSearchBroadcastReceiver);
unregisterReceiver(mWifiConnectBroadcastReceiver);
} private void initWifiSate() { //wifi 搜索结果接收广播
mWifiSearchBroadcastReceiver = new BroadcastReceiver() { @Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {// 扫描结果改表
mScanResultList = WifiAutoConnectManager.getScanResults();
if (mWifiListAdapter != null) { mWifiListAdapter.setmWifiList(mScanResultList); mWifiListAdapter.notifyDataSetChanged(); }
}
} }; mWifiSearchIntentFilter = new IntentFilter();
mWifiSearchIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
mWifiSearchIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
mWifiSearchIntentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION); //wifi 状态变化接收广播
mWifiConnectBroadcastReceiver = new BroadcastReceiver() { @Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
int wifState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
if (wifState != WifiManager.WIFI_STATE_ENABLED) {
Toast.makeText(WifiTestActivity.this, "没有wifi", Toast.LENGTH_SHORT).show();
}
} else if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
int linkWifiResult = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, 123);
Log.e("wifidemo", ssid + "linkWifiResult:" + linkWifiResult);
if (linkWifiResult == WifiManager.ERROR_AUTHENTICATING) {
Log.e("wifidemo", ssid + "onReceive:密码错误");
}
} else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo.DetailedState state = ((NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO)).getDetailedState();
setWifiState(state);
}
}
}; mWifiConnectIntentFilter = new IntentFilter();
mWifiConnectIntentFilter.addAction(WifiManager.ACTION_PICK_WIFI_NETWORK);
mWifiConnectIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
mWifiConnectIntentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
mWifiConnectIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); } /**
* 显示wifi状态
*
* @param state
*/
@SuppressLint("NewApi")
public void setWifiState(final NetworkInfo.DetailedState state) {
if (state == NetworkInfo.DetailedState.AUTHENTICATING) { } else if (state == NetworkInfo.DetailedState.BLOCKED) { } else if (state == NetworkInfo.DetailedState.CONNECTED) {
progressbar.setVisibility(View.GONE);
isLinked = true;
mWifiState.setText("wifi state:连接成功");
mWifiName.setText("wifi name:" + WifiAutoConnectManager.getSSID());
mIP.setText("ip address:" + WifiAutoConnectManager.getIpAddress());
mGateway.setText("gateway:" + WifiAutoConnectManager.getGateway());
mMac.setText("mac:" + WifiAutoConnectManager.getMacAddress());
gateway = WifiAutoConnectManager.getGateway();
mac = WifiAutoConnectManager.getMacAddress();
} else if (state == NetworkInfo.DetailedState.CONNECTING) {
isLinked = false;
mWifiState.setText("wifi state:连接中...");
mWifiName.setText("wifi name:" + WifiAutoConnectManager.getSSID());
mIP.setText("ip address");
mGateway.setText("gateway");
} else if (state == NetworkInfo.DetailedState.DISCONNECTED) {
isLinked = false;
mWifiState.setText("wifi state:断开连接");
mWifiName.setText("wifi name");
mIP.setText("ip address");
mGateway.setText("gateway");
} else if (state == NetworkInfo.DetailedState.DISCONNECTING) {
isLinked = false;
mWifiState.setText("wifi state:断开连接中...");
} else if (state == NetworkInfo.DetailedState.FAILED) {
isLinked = false;
mWifiState.setText("wifi state:连接失败");
} else if (state == NetworkInfo.DetailedState.IDLE) { } else if (state == NetworkInfo.DetailedState.OBTAINING_IPADDR) { } else if (state == NetworkInfo.DetailedState.SCANNING) { } else if (state == NetworkInfo.DetailedState.SUSPENDED) { }
} private void intiView() { progressbar = (FrameLayout) findViewById(R.id.progressbar);
mWifiState = (TextView) findViewById(R.id.wifi_state);
mWifiName = (TextView) findViewById(R.id.wifi_name);
mMac = (TextView) findViewById(R.id.wifi_mac);
mIP = (TextView) findViewById(R.id.ip_address);
mGateway = (TextView) findViewById(R.id.ip_gateway);
mListWifi = (ListView) findViewById(R.id.list_wifi);
mBtnSearch = (Button) findViewById(R.id.search_wifi);
mBtnConnect = (Button) findViewById(R.id.connect_wifi); et_pwd = (EditText) findViewById(R.id.et_pwd); mBtnSearch.setOnClickListener(this);
mBtnConnect.setOnClickListener(this); mListWifi.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
mWifiListAdapter.setSelectItem(i); mWifiListAdapter.notifyDataSetChanged(); ScanResult scanResult = mScanResultList.get(i);
ssid = scanResult.SSID;
type = WifiAutoConnectManager.getCipherType(ssid);
}
});
} @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case WIFI_SCAN_PERMISSION_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { } else {
// 不允许
Toast.makeText(this, "开启权限失败", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
} /**
* 获取wifi列表
*/
private class WorkAsyncTask extends AsyncTask<Void, Void, List<ScanResult>> {
private List<ScanResult> mScanResult = new ArrayList<>(); @Override
protected void onPreExecute() {
super.onPreExecute();
progressbar.setVisibility(View.VISIBLE);
} @Override
protected List<ScanResult> doInBackground(Void... params) {
if (WifiAutoConnectManager.startStan()) {
mScanResult = WifiAutoConnectManager.getScanResults();
}
List<ScanResult> filterScanResultList = new ArrayList<>();
if (mScanResult != null) {
for (ScanResult wifi : mScanResult) {
filterScanResultList.add(wifi);
Log.e("wifidemo", "doInBackground: wifi:" + wifi);
}
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return filterScanResultList;
} @Override
protected void onPostExecute(final List<ScanResult> result) {
super.onPostExecute(result);
progressbar.setVisibility(View.GONE);
mScanResultList = result;
mWifiListAdapter = new WifiListAdapter(result, LayoutInflater.from(WifiTestActivity.this)); mListWifi.setAdapter(mWifiListAdapter); }
} /**
* wifi列表适配器
*/
class WifiListAdapter extends BaseAdapter { private List<ScanResult> mWifiList;
private LayoutInflater mLayoutInflater; public WifiListAdapter(List<ScanResult> wifiList, LayoutInflater layoutInflater) {
this.mWifiList = wifiList;
this.mLayoutInflater = layoutInflater;
} @Override
public int getCount() {
return mWifiList.size();
} @Override
public Object getItem(int position) {
return mWifiList.get(position);
} @Override
public long getItemId(int position) {
return position;
} @Override
public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) {
convertView = mLayoutInflater.inflate(R.layout.fragment_wifi_list_item, null);
}
ScanResult sr = mWifiList.get(position);
convertView.setTag(sr);
TextView textView = (TextView) convertView.findViewById(R.id.wifi_item_name);
int numLevel = WifiAutoConnectManager.getSignalNumsLevel(sr.level, 5);
String password = sr.capabilities;
String text = "加密方式:";
if (password.contains("WPA") || password.contains("wpa")) {
password = "WPA";
} else if (password.contains("WEP") || password.contains("wep")) {
password = "WEP";
} else {
text = "";
password = "";
}
textView.setText(sr.SSID + " " + text + password + " 信号强度:" + numLevel);
convertView.setBackgroundColor(Color.WHITE);
if (position == selectItem) {
convertView.setBackgroundColor(Color.GRAY);
}
return convertView;
} public void setSelectItem(int selectItem) {
this.selectItem = selectItem;
} private int selectItem = -1; public void setmWifiList(List<ScanResult> mWifiList) {
this.mWifiList = mWifiList;
}
} /**
* 连接指定的wifi
*/
class ConnectAsyncTask extends AsyncTask<Void, Void, Boolean> {
private String ssid;
private String password;
private WifiAutoConnectManager.WifiCipherType type;
WifiConfiguration tempConfig; public ConnectAsyncTask(String ssid, String password, WifiAutoConnectManager.WifiCipherType type) {
this.ssid = ssid;
this.password = password;
this.type = type;
} @Override
protected void onPreExecute() {
super.onPreExecute();
progressbar.setVisibility(View.VISIBLE);
} @Override
protected Boolean doInBackground(Void... voids) {
// 打开wifi
mWifiAutoConnectManager.openWifi();
// 开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右),所以要等到wifi
// 状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句
while (mWifiAutoConnectManager.wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
try {
// 为了避免程序一直while循环,让它睡个100毫秒检测……
Thread.sleep(100); } catch (InterruptedException ie) {
Log.e("wifidemo", ie.toString());
}
} tempConfig = mWifiAutoConnectManager.isExsits(ssid);
//禁掉所有wifi
for (WifiConfiguration c : mWifiAutoConnectManager.wifiManager.getConfiguredNetworks()) {
mWifiAutoConnectManager.wifiManager.disableNetwork(c.networkId);
} if (tempConfig != null) {
Log.d("wifidemo", ssid + "配置过!");
boolean result = mWifiAutoConnectManager.wifiManager.enableNetwork(tempConfig.networkId, true);
if (!isLinked && type != WifiAutoConnectManager.WifiCipherType.WIFICIPHER_NOPASS) {
try {
Thread.sleep(5000);//超过5s提示失败
if (!isLinked) {
Log.d("wifidemo", ssid + "连接失败!");
Log.d("wifidemo", ssid + "连接失败!");
//mWifiAutoConnectManager.wifiManager.disableNetwork(tempConfig.networkId);
Log.d("wifidemo", "----------------"+ssid+"重新连接中.....");
//如果连接失败 删除原来的networkId 重新假如
mWifiAutoConnectManager.wifiManager.removeNetwork(tempConfig.networkId);
WifiConfiguration wifiConfig = mWifiAutoConnectManager.createWifiInfo(ssid, password, type);
int netID = mWifiAutoConnectManager.wifiManager.addNetwork(wifiConfig);
boolean enabled = mWifiAutoConnectManager.wifiManager.enableNetwork(netID, true);
Log.d("wifidemo", "enableNetwork status enable=" + enabled);
//
}
} catch (Exception e) {
e.printStackTrace();
}
}
Log.d("wifidemo", "result=" + result);
return result;
} else {
Log.d("wifidemo", ssid + "没有配置过!");
if (type != WifiAutoConnectManager.WifiCipherType.WIFICIPHER_NOPASS) {
runOnUiThread(new Runnable() {
@Override
public void run() {
final EditText inputServer = new EditText(WifiTestActivity.this);
new AlertDialog.Builder(WifiTestActivity.this)
.setTitle("请输入密码")
.setView(inputServer)
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setPositiveButton("连接", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) {
password = inputServer.getText().toString();
new Thread(new Runnable() {
@Override
public void run() {
WifiConfiguration wifiConfig = mWifiAutoConnectManager.createWifiInfo(ssid, password,
type);
if (wifiConfig == null) {
Log.d("wifidemo", "wifiConfig is null!");
return;
}
Log.d("wifidemo", wifiConfig.SSID); int netID = mWifiAutoConnectManager.wifiManager.addNetwork(wifiConfig);
boolean enabled = mWifiAutoConnectManager.wifiManager.enableNetwork(netID, true);
Log.d("wifidemo", "enableNetwork status enable=" + enabled);
// Log.d("wifidemo", "enableNetwork connected=" + mWifiAutoConnectManager.wifiManager.reconnect());
// mWifiAutoConnectManager.wifiManager.reconnect();
}
}).start();
}
}).show();
}
});
} else {
WifiConfiguration wifiConfig = mWifiAutoConnectManager.createWifiInfo(ssid, password, type);
if (wifiConfig == null) {
Log.d("wifidemo", "wifiConfig is null!");
return false;
}
Log.d("wifidemo", wifiConfig.SSID);
int netID = mWifiAutoConnectManager.wifiManager.addNetwork(wifiConfig);
boolean enabled = mWifiAutoConnectManager.wifiManager.enableNetwork(netID, true);
Log.d("wifidemo", "enableNetwork status enable=" + enabled);
// Log.d("wifidemo", "enableNetwork connected=" + mWifiAutoConnectManager.wifiManager.reconnect());
// return mWifiAutoConnectManager.wifiManager.reconnect();
return enabled;
}
return false; }
} @Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
mConnectAsyncTask = null;
}
} }
4、WifiAutoConnectManager
package com.example.helloword.utils; import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit; import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.util.Log; public class WifiAutoConnectManager { private static final String TAG = WifiAutoConnectManager.class
.getSimpleName(); public static WifiManager wifiManager = null;
private static WifiAutoConnectManager mWifiAutoConnectManager; // 定义几种加密方式,一种是WEP,一种是WPA,还有没有密码的情况
public enum WifiCipherType {
WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
} // 构造函数
private WifiAutoConnectManager(WifiManager wifiManager) {
this.wifiManager = wifiManager;
} public static WifiAutoConnectManager newInstance(WifiManager wifiManager) {
if (mWifiAutoConnectManager == null) {
mWifiAutoConnectManager = new WifiAutoConnectManager(wifiManager);
}
return mWifiAutoConnectManager;
} // 查看以前是否也配置过这个网络
public WifiConfiguration isExsits(String SSID) {
List<WifiConfiguration> existingConfigs = wifiManager
.getConfiguredNetworks();
for (WifiConfiguration existingConfig : existingConfigs) {
if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
return existingConfig;
}
}
return null;
} /**
* 创建wifi配置文件
*
* @param SSID
* @param Password
* @param Type
* @return
*/
public WifiConfiguration createWifiInfo(String SSID, String Password, WifiCipherType Type) {
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + SSID + "\"";
// config.SSID = SSID;
// nopass
if (Type == WifiCipherType.WIFICIPHER_NOPASS) {
// config.wepKeys[0] = "";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
// config.wepTxKeyIndex = 0;
} else if (Type == WifiCipherType.WIFICIPHER_WEP) {// wep
if (!TextUtils.isEmpty(Password)) {
if (isHexWepKey(Password)) {
config.wepKeys[0] = Password;
} else {
config.wepKeys[0] = "\"" + Password + "\"";
}
}
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
} else if (Type == WifiCipherType.WIFICIPHER_WPA) {// wpa
config.preSharedKey = "\"" + Password + "\"";
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
config.status = WifiConfiguration.Status.ENABLED;
}
return config;
} // 打开wifi功能
public boolean openWifi() {
boolean bRet = true;
if (!wifiManager.isWifiEnabled()) {
bRet = wifiManager.setWifiEnabled(true);
}
return bRet;
} // 关闭WIFI
private void closeWifi() {
if (wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
}
} private static boolean isHexWepKey(String wepKey) {
final int len = wepKey.length(); // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?)
if (len != 10 && len != 26 && len != 58) {
return false;
} return isHex(wepKey);
} private static boolean isHex(String key) {
for (int i = key.length() - 1; i >= 0; i--) {
final char c = key.charAt(i);
if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a'
&& c <= 'f')) {
return false;
}
} return true;
} /**
* 根据给定的ssid信号量和总级别,判断当前信号量,在什么级别
*
* @param rssi
* @param numLevels
* @return
*/
public static int getSignalNumsLevel(int rssi, int numLevels) {
if (wifiManager == null) {
return -1;
}
return WifiManager.calculateSignalLevel(rssi, numLevels);
} /**
* 获取ssid的加密方式
*/
public static WifiCipherType getCipherType(String ssid) {
if (wifiManager == null) {
return null;
}
List<ScanResult> list = wifiManager.getScanResults(); for (ScanResult scResult : list) { if (!TextUtils.isEmpty(scResult.SSID) && scResult.SSID.equals(ssid)) {
String capabilities = scResult.capabilities;
if (!TextUtils.isEmpty(capabilities)) { if (capabilities.contains("WPA")
|| capabilities.contains("wpa")) {
Log.e("wifidemo", "wpa");
return WifiCipherType.WIFICIPHER_WPA;
} else if (capabilities.contains("WEP")
|| capabilities.contains("wep")) {
Log.e("wifidemo", "wep");
return WifiCipherType.WIFICIPHER_WEP;
} else {
Log.e("wifidemo", "no");
return WifiCipherType.WIFICIPHER_NOPASS;
}
}
}
}
return WifiCipherType.WIFICIPHER_INVALID;
} /**
* 获取 bssid 接入点的地址
* @return
*/
public static String getBSSID() {
if (wifiManager == null) {
return null;
}
WifiInfo info = wifiManager.getConnectionInfo();
Log.e("wifidemo", "getBSSID" + info.getBSSID());
if (info == null) {
return null;
}
return info.getBSSID();
} /**
* 获取网关地址
*
* @return
*/
public static String getGateway() {
if (wifiManager == null) {
return "";
}
InetAddress inetAddress = NetWorkUtils.intToInetAddress(wifiManager.getDhcpInfo().gateway);
if (inetAddress == null) {
return "";
}
return inetAddress.getHostAddress();
} /**
* 获取ip地址
* @return
*/
public static String getIpAddress(){
if (wifiManager == null) {
return "";
}
InetAddress inetAddress = NetWorkUtils.intToInetAddress(wifiManager.getConnectionInfo().getIpAddress());
if (inetAddress == null) {
return "";
}
return inetAddress.getHostAddress();
}
/**
* 获取mac地址
* @return
*/
public static String getMacAddress(){
if (wifiManager == null) {
return "";
}
return wifiManager.getConnectionInfo().getMacAddress();
}
/**
* 获取wifi名称
*
* @return
*/
public static String getSSID() {
if (wifiManager == null) {
return null;
}
WifiInfo info = wifiManager.getConnectionInfo();
String ssid = info.getSSID();
if (ssid != null) {
ssid = ssid.substring(1, ssid.length() - 1);
}
return ssid;
} /**
* 扫描WIFI AP
*/
public static boolean startStan() {
if (wifiManager == null) {
return false;
} if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true); try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return wifiManager.startScan();
} /**
* 获取所有WIFI AP
*/
public static List<ScanResult> getScanResults() {
List<ScanResult> srList = wifiManager.getScanResults();
if (srList == null) {
srList = new ArrayList<ScanResult>();
}
return srList;
}
}
5、在清单文件中设置wifi权限
<uses-permission android:name="android.permission.INTERNET" />
<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_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
6、demo源码:
https://github.com/hongchuanfeng/WifiDemo
android 连接wifi案例的更多相关文章
- Android 连接Wifi和创建Wifi热点 demo
android的热点功能不可见,用了反射的技术搞定之外. Eclipse设置语言为utf-8才能查看中文注释 上代码: MainActivity.java package com.widget.hot ...
- Android连接wifi,调用系统API【转】
本文转载自:http://blog.csdn.net/aaa1050070637/article/details/54136472 直接上代码,简单粗暴,一看就懂 import android.con ...
- 我的Android进阶之旅------>Android检测wifi连接状态
今天要实现监听系统Wifi连接状态,下面代码简化后提取出来的,以备后用. step1. 编写BroadcastReceiver import android.content.BroadcastRece ...
- android开发连接wifi addNetwork 返回-1
如下代码:(注释掉的是会返回-1的代码,未注释的是能够正常连接wifi的代码) // public WifiConfiguration CreateWifiInfo(String SSID, Stri ...
- 【Android开发—智能家居系列】(三):手机连接WIFI模块
版权声明:本文为博主原创文章,未经博主允许不得转载. 目录(?)[+] 概述 实现连接WIFI的功能会用到一个工具类,源码可以点击链接下载.网上这些类似的工具类里的代码差不多是一样的.连接无线网主要有 ...
- android推断是否连接wifi和网络状态的推断
<span style="font-size:18px;">// 是否连接WIFI public static boolean isWifiConnected(Cont ...
- 【移动开发】Android中WIFI开发总结(二)
搞了好几天终于有点眉目了,这里接着总结一下Android中WiFi的使用,在前面(http://smallwoniu.blog.51cto.com/3911954/1334951)我们已经简单了解了W ...
- 【Android】wifi开发
WIFI就是一种无线联网技术,常见的是使用无线路由器.那么在这个无线路由器的信号覆盖的范围内都可以采用WIFI连接的方式进行联网.如果无线路由器连接了一个ADSL线路或其他的联网线路,则又被称为“热点 ...
- android.net.wifi的简单使用方法
获取Wifi的控制类WifiManager. WifiManager wm=(WifiManager)getSystemService(Context.WIFI_SERVICE); 接下来可以对w ...
随机推荐
- Codeforces Beta Round #19
A. World Football Cup #include <bits/stdc++.h> using namespace std; ; char name[N][N]; map&l ...
- Java的静态变量初始化的坑
在网上看到一个很有意思的题目,题目如下 class SingleTon { private static SingleTon singleTon = new SingleTon(); public s ...
- 【pytorch】持续踩坑 & 错误解决经历
报错 1.[invalid argument 0: Sizes of tensors must match except in dimension 0.] {出现在 torch.utils.data. ...
- hibernate关联关系 (多对多)
hibernate的多对多 hibernate可以直接映射多对多关联关系(看作两个一对多 多对多关系注意事项 一定要定义一个主控方 多对多删除 主控方直接删除 被控方先通过主控方解除多对多关系,再删 ...
- 网络协议 9 - TCP协议(下)
上次了解了 TCP 建立连接与断开连接的过程,我们发现,TCP 会通过各种“套路”来保证传输数据的安全.除此之外,我们还大概了解了 TCP 包头格式所对应解决的五个问题:顺序问题.丢包问题.连接维护. ...
- 第02组 Alpha冲刺(2/4)
队名:十一个憨批 组长博客 作业博客 组长黄智 过去两天完成的任务:写博客,复习C语言 GitHub签入记录 接下来的计划:构思游戏实现 还剩下哪些任务:敲代码 燃尽图 遇到的困难:Alpha冲刺时间 ...
- 【cf补题记录】Codeforces Round #608 (Div. 2)
比赛传送门 再次改下写博客的格式,以锻炼自己码字能力 A. Suits 题意:有四种材料,第一套西装需要 \(a\).\(d\) 各一件,卖 \(e\) 块:第二套西装需要 \(b\).\(c\).\ ...
- React创建组件的方法,组件的props属性、state属性的用法和特点,父子组件传值,兄弟组件传值
创建组件的方法,组件的props属性.state属性的用法和特点,父子组件传值,兄弟组件传值 1.react组件 1.1.创建组件的方法 1.1.1.函数组件 定义一个组件最简单的方式是使用JavaS ...
- 使用docker部署nginx+tomcat架构
架构说明: 使用nginx+tomcat实现动态/静态(资源请求)分离和负载均衡. 参考文档: https://www.runoob.com/docker/docker-tutorial.html 配 ...
- IOCP另一种实现
参考 https://docs.microsoft.com/zh-cn/windows/win32/api/winbase/nf-winbase-bindiocompletioncallback ht ...