安卓系统设置之Wifi连接
在网上查了很多资料,但是有的是无法连接免费的wifi,有的是无法使用,后来找到一个好用的wifi连接,但是忘了是哪篇 - -
直接上代码了
1.MainActivity
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
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;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.futurus.hud.setting.R;
import com.futurus.hud.setting.adapter.WifiAdapter;
import com.futurus.hud.setting.base.BaseActivity;
import java.util.List;
public class WifiActivity extends BaseActivity {
private static final String TAG = "WifiActivity";
private Button mBtnWifiToggle;
private WifiManager mWifiManager;
private ListView mLvWifiList;
private WifiAdapter mAdapter;
private TextView mTxtSearch;
private WifiConfiguration config;
private static final int WIFICIPHER_NOPASS = 1;
private static final int WIFICIPHER_WEP = 2;
private static final int WIFICIPHER_WPA = 3;
private TextView text_state;
//没10s 刷新
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
while (!thread.isInterrupted()) {
Thread.sleep(10000);
search();
}
} catch (Exception e) {
Log.e(TAG, "run: " + e.toString());
}
}
});
@Override
public int getLayout() {
return R.layout.activity_wifi;
}
@Override
public void initView() {
mWifiManager = (WifiManager) this
.getSystemService(Context.WIFI_SERVICE);
mBtnWifiToggle = (Button) findViewById(R.id.wifi_toggle);
mLvWifiList = (ListView) findViewById(R.id.wifi_lv);
mTxtSearch = (TextView) findViewById(R.id.wifi_search);
text_state = (TextView) findViewById(R.id.text_state);
initBroadcastReceiver();
thread.start();
mAdapter = new WifiAdapter(this, R.layout.item_wifi2);
mLvWifiList.setAdapter(mAdapter);
mLvWifiList.setSelector(R.drawable.selector_setting_list_item);
}
@Override
public void initData() {
mLvWifiList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mWifiManager.disconnect();
final ScanResult scanResult = (ScanResult) mAdapter.getItem(position);
String capabilities = scanResult.capabilities;
int type = WIFICIPHER_WPA;
if (!TextUtils.isEmpty(capabilities)) {
if (capabilities.contains("WPA") || capabilities.contains("wpa")) {
type = WIFICIPHER_WPA;
} else if (capabilities.contains("WEP") || capabilities.contains("wep")) {
type = WIFICIPHER_WEP;
} else {
type = WIFICIPHER_NOPASS;
}
}
config = isExsits(scanResult.SSID);
if (config == null) {
if (type != WIFICIPHER_NOPASS) {//需要密码
final int finalType = type;
Intent intent = new Intent(WifiActivity.this, InputPwActivity.class);
intent.putExtra("item", scanResult.SSID);
intent.putExtra("type", finalType);
startActivityForResult(intent, 0);
} else {
config = createWifiInfo(scanResult.SSID, "", type);
connect(config);
}
} else {
connect(config);
}
}
});
}
@Override
protected void onResume() {
checkWifiState();
super.onResume();
}
private void connect(WifiConfiguration config) {
text_state.setText("连接中...");
int wcgID = mWifiManager.addNetwork(config);
mWifiManager.enableNetwork(wcgID, true);
}
private void initBroadcastReceiver() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(receiver, intentFilter);
}
//点击事件
public void wifiToggle(View view) {
if (wifiIsOpen()) {
mBtnWifiToggle.setCompoundDrawablesRelativeWithIntrinsicBounds(0,
0, R.drawable.close, 0);
mWifiManager.setWifiEnabled(false);
mBtnWifiToggle.setClickable(false);
} else if (!wifiIsOpen()) {
mBtnWifiToggle.setCompoundDrawablesRelativeWithIntrinsicBounds(0,
0, R.drawable.open, 0);
mWifiManager.setWifiEnabled(true);
mBtnWifiToggle.setClickable(false);
}
checkWifiState();
search();
}
//检查状态
public void checkWifiState() {
Log.e(TAG, "checkWifiState: " + wifiIsOpen());
if (wifiIsOpen()) {
mBtnWifiToggle.setCompoundDrawablesRelativeWithIntrinsicBounds(0,
0, R.drawable.open, 0);
if (mAdapter.getCount() != 0) {
mLvWifiList.setVisibility(View.VISIBLE);
mTxtSearch.setVisibility(View.GONE);
} else {
mLvWifiList.setVisibility(View.GONE);
mTxtSearch.setVisibility(View.VISIBLE);
}
mBtnWifiToggle.setText("开");
text_state.setVisibility(View.VISIBLE);
} else if (!wifiIsOpen()) {
mBtnWifiToggle.setCompoundDrawablesRelativeWithIntrinsicBounds(0,
0, R.drawable.close, 0);
mLvWifiList.setVisibility(View.GONE);
mTxtSearch.setVisibility(View.GONE);
mBtnWifiToggle.setText("关");
text_state.setVisibility(View.GONE);
}
mBtnWifiToggle.setClickable(true);
}
public boolean wifiIsOpen() {
return mWifiManager.isWifiEnabled();
}
/**
* 搜索wifi热点
*/
private void search() {
checkWifiState();
mWifiManager.startScan();
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
Log.w("BBB", "SCAN_RESULTS_AVAILABLE_ACTION");
// wifi已成功扫描到可用wifi。
List<ScanResult> scanResults = mWifiManager.getScanResults();
mAdapter.clear();
mAdapter.addAll(scanResults);
} else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
Log.w("BBB", "WifiManager.WIFI_STATE_CHANGED_ACTION");
int wifiState = intent.getIntExtra(
WifiManager.EXTRA_WIFI_STATE, 0);
switch (wifiState) {
case WifiManager.WIFI_STATE_ENABLED:
//获取到wifi开启的广播时,开始扫描
mWifiManager.startScan();
break;
case WifiManager.WIFI_STATE_DISABLED:
//wifi关闭发出的广播
break;
}
} else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
Log.w("BBB", "WifiManager.NETWORK_STATE_CHANGED_ACTION");
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
text_state.setText("连接已断开");
text_state.setTextColor(Color.WHITE);
} else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo wifiInfo = wifiManager.getConnectionInfo();
text_state.setText("已连接到网络:" + wifiInfo.getSSID());
text_state.setTextColor(getResources().getColor(R.color.textColor));
} else {
NetworkInfo.DetailedState state = info.getDetailedState();
text_state.setTextColor(getResources().getColor(R.color.textColor));
if (state == state.CONNECTING) {
text_state.setText("连接中...");
} else if (state == state.AUTHENTICATING) {
text_state.setText("正在验证身份信息...");
} else if (state == state.OBTAINING_IPADDR) {
text_state.setText("正在获取IP地址...");
} else if (state == state.FAILED) {
text_state.setText("连接失败");
}
}
}
checkWifiState();
}
};
/**
* 判断当前wifi是否有保存
*
* @param SSID
* @return
*/
private WifiConfiguration isExsits(String SSID) {
List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
for (WifiConfiguration existingConfig : existingConfigs) {
if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
return existingConfig;
}
}
return null;
}
public WifiConfiguration createWifiInfo(String SSID, String password,
int type) {
Log.w("AAA", "SSID = " + SSID + "password " + password + "type ="
+ type);
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + SSID + "\"";
if (type == WIFICIPHER_NOPASS) {
config.wepKeys[0] = "\"" + "\"";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
} else if (type == WIFICIPHER_WEP) {
config.preSharedKey = "\"" + password + "\"";
config.hiddenSSID = true;
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;
} else if (type == 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;
} else {
return null;
}
return config;
}
@Override
protected void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
//获取输入的密码
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == 1) {
String password = data.getStringExtra("password");
String ssid = data.getStringExtra("ssid");
int type = data.getIntExtra("type", -1);
config = createWifiInfo(ssid, password, type);
connect(config);
}
}
}
2 . 网上都有类似的Utils类 - - wifiUtils
public class WifiUtils {
//定义几种加密方式,一种是WEP,一种是WPA,还有没有密码的情况
public enum WifiCipherType
{
WIFICIPHER_WEP,WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
}
private static final String TAG = "WifiUtils";
private WifiManager localWifiManager;//提供Wifi管理的各种主要API,主要包含wifi的扫描、建立连接、配置信息等
//private List<ScanResult> wifiScanList;//ScanResult用来描述已经检测出的接入点,包括接入的地址、名称、身份认证、频率、信号强度等
private List<WifiConfiguration> wifiConfigList;//WIFIConfiguration描述WIFI的链接信息,包括SSID、SSID隐藏、password等的设置
private WifiInfo wifiConnectedInfo;//已经建立好网络链接的信息
private WifiManager.WifiLock wifiLock;//阻止WIFI也进入睡眠状态及WIFI的关闭
public WifiUtils( Context context){
localWifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
}
//检查WIFI状态
public int WifiCheckState(){
return localWifiManager.getWifiState();
}
//开启WIFI
public void WifiOpen(){
if(!localWifiManager.isWifiEnabled()){
localWifiManager.setWifiEnabled(true);
}
}
//关闭WIFI
public void WifiClose(){
if(!localWifiManager.isWifiEnabled()){
localWifiManager.setWifiEnabled(false);
}
}
//扫描wifi
public void WifiStartScan(){
localWifiManager.startScan();
}
//得到Scan结果
public List<ScanResult> getScanResults(){
return localWifiManager.getScanResults();//得到扫描结果
}
//Scan结果转为Sting
public List<String> scanResultToString(List<ScanResult> list){
List<String> strReturnList = new ArrayList<String>();
for(int i = 0; i < list.size(); i++){
ScanResult strScan = list.get(i);
String str = strScan.toString();
boolean bool = strReturnList.add(str);
if(!bool){
Log.i("scanResultToSting","Addfail");
}
}
return strReturnList;
}
//得到Wifi配置好的信息
public void getConfiguration(){
wifiConfigList = localWifiManager.getConfiguredNetworks();//得到配置好的网络信息
for(int i =0;i<wifiConfigList.size();i++){
Log.i("getConfiguration",wifiConfigList.get(i).SSID);
Log.i("getConfiguration",String.valueOf(wifiConfigList.get(i).networkId));
}
}
//判定指定WIFI是否已经配置好,依据WIFI的地址BSSID,返回NetId
public int IsConfiguration(String SSID){
// Log.i("IsConfiguration",String.valueOf(wifiConfigList.size()));
for(int i = 0; i < wifiConfigList.size(); i++){
Log.i(wifiConfigList.get(i).SSID,String.valueOf( wifiConfigList.get(i).networkId));
if(wifiConfigList.get(i).SSID.equals(SSID)){//地址相同
return wifiConfigList.get(i).networkId;
}
}
return -1;
}
public WifiConfiguration IsExsits(String SSID)
{
List<WifiConfiguration> existingConfigs = localWifiManager.getConfiguredNetworks();
for (WifiConfiguration existingConfig : existingConfigs)
{
if (existingConfig.SSID.equals("\""+SSID+"\""))
{
return existingConfig;
}
}
return null;
}
//添加指定WIFI的配置信息,原列表不存在此SSID
public int AddWifiConfig(List<ScanResult> wifiList,String ssid,String pwd){
int wifiId = -1;
for(int i = 0;i < wifiList.size(); i++){
ScanResult wifi = wifiList.get(i);
if(wifi.SSID.equals(ssid)){
Log.i("AddWifiConfig","equals");
WifiConfiguration wifiCong = new WifiConfiguration();
wifiCong.SSID = "\""+wifi.SSID+"\"";//\"转义字符,代表"
wifiCong.preSharedKey = "\""+pwd+"\"";//WPA-PSK密码
wifiCong.hiddenSSID = false;
wifiCong.status = WifiConfiguration.Status.ENABLED;
wifiId = localWifiManager.addNetwork(wifiCong);//将配置好的特定WIFI密码信息添加,添加完成后默认是不激活状态,成功返回ID,否则为-1
if(wifiId != -1){
return wifiId;
}
}
}
return wifiId;
}
//连接指定Id的WIFI
public boolean ConnectWifi(int wifiId){
for(int i = 0; i < wifiConfigList.size(); i++){
WifiConfiguration wifi = wifiConfigList.get(i);
if(wifi.networkId == wifiId){
while(!(localWifiManager.enableNetwork(wifiId, true))){//激活该Id,建立连接
Log.i("ConnectWifi",String.valueOf(wifiConfigList.get(wifiId).status));//status:0--已经连接,1--不可连接,2--可以连接
}
return true;
}
}
return false;
}
//创建一个WIFILock
public void createWifiLock(String lockName){
wifiLock = localWifiManager.createWifiLock(lockName);
}
//锁定wifilock
public void acquireWifiLock(){
wifiLock.acquire();
}
//解锁WIFI
public void releaseWifiLock(){
if(wifiLock.isHeld()){//判定是否锁定
wifiLock.release();
}
}
//得到建立连接的信息
public void getConnectedInfo(){
wifiConnectedInfo = localWifiManager.getConnectionInfo();
}
//得到连接的MAC地址
public String getConnectedMacAddr(){
return (wifiConnectedInfo == null)? "NULL":wifiConnectedInfo.getMacAddress();
}
//得到连接的名称SSID
public String getConnectedSSID(){
return (wifiConnectedInfo == null)? "NULL":wifiConnectedInfo.getSSID();
}
//得到连接的IP地址
public int getConnectedIPAddr(){
return (wifiConnectedInfo == null)? 0:wifiConnectedInfo.getIpAddress();
}
//得到连接的ID
public int getConnectedID(){
return (wifiConnectedInfo == null)? 0:wifiConnectedInfo.getNetworkId();
}
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 + "\"";
if(Type == WifiCipherType.WIFICIPHER_NOPASS)
{
config.wepKeys[0] = "";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if(Type == WifiCipherType.WIFICIPHER_WEP)
{
config.preSharedKey = "\""+Password+"\"";
config.hiddenSSID = true;
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 == WifiCipherType.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.status = WifiConfiguration.Status.ENABLED;
}
else
{
return null;
}
return config;
}
}
3 .可以实时跟新状态的adapter (我的baseadapter无法更新了….)
public class WifiAdapter extends ArrayAdapter<ScanResult> {
private final LayoutInflater mInflater;
private int mResource;
public static final String WIFI_AUTH_OPEN = "";
public static final String WIFI_AUTH_ROAM = "[ESS]";
public WifiAdapter(Context context, int resource) {
super(context, resource);
mInflater = LayoutInflater.from(context);
mResource = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(mResource, parent, false);
}
TextView name = (TextView) convertView.findViewById(R.id.item_wifi_name);
ImageView signl = (ImageView) convertView.findViewById(R.id.item_wifi_signal);
ScanResult scanResult = getItem(position);
name.setText(scanResult.SSID);
String capabilities = scanResult.capabilities;
int level = scanResult.level;
level = WifiManager.calculateSignalLevel(level, 100);
if (capabilities != null
&& (capabilities.equals(WIFI_AUTH_OPEN) || capabilities
.equals(WIFI_AUTH_ROAM))) {
if (level >= 0 && level <= 25) {
signl
.setImageResource(R.drawable.icon_wifi_signal_1);
} else if (level > 25 && level <= 50) {
signl
.setImageResource(R.drawable.icon_wifi_signal_2);
} else if (level > 50 && level <= 75) {
signl
.setImageResource(R.drawable.icon_wifi_signal_3);
} else if (level > 75 && level <= 100) {
signl
.setImageResource(R.drawable.icon_wifi_signal_4);
}
} else {
if (level >= 0 && level <= 25) {
signl
.setImageResource(R.drawable.icon_wifi_lock_signal_1);
} else if (level > 25 && level <= 50) {
signl
.setImageResource(R.drawable.icon_wifi_lock_signal_2);
} else if (level > 50 && level <= 75) {
signl
.setImageResource(R.drawable.icon_wifi_lock_signal_3);
} else if (level > 75 && level <= 100) {
signl
.setImageResource(R.drawable.icon_wifi_lock_signal_4);
}
}
return convertView;
}
}
4 . 输入密码的界面
public class InputPwActivity extends BaseActivity implements View.OnClickListener {
private Button mBtnReady;
private Button mBtnCancel;
private EditText mEditTextPw;
private CheckBox mCheckPw;
private String ssid;
private int type;
Runnable run2 = new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
View rootview = InputPwActivity.this.getWindow().getDecorView();
View aaa = rootview.findFocus();
Log.i("tag", aaa.toString());
}
}
};
private CheckBox mCheck;
@Override
public int getLayout() {
return R.layout.activity_input_pw;
}
@Override
public void initView() {
Intent intent = getIntent();
ssid = intent.getStringExtra("item");
type = intent.getIntExtra("type", -1);
mBtnReady = (Button) findViewById(R.id.btn_ready);
mBtnCancel = (Button) findViewById(R.id.btn_cancel);
mEditTextPw = (EditText) findViewById(R.id.wifi_password);
// new Thread(run2).start();
mCheckPw = (CheckBox) findViewById(R.id.wifi_check);
mBtnReady.setOnClickListener(this);
mBtnCancel.setOnClickListener(this);
mEditTextPw.setOnClickListener(this);
}
@Override
public void initData() {
if (mCheckPw.isChecked()) {
mEditTextPw.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
} else {
mEditTextPw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_ready:
if(!TextUtils.isEmpty(mEditTextPw.getText())){
String trim = mEditTextPw.getText().toString().trim();
Intent intent = new Intent();
intent.putExtra("password", trim);
intent.putExtra("ssid", ssid);
intent.putExtra("type", type);
setResult(1, intent);
}
finish();
break;
case R.id.btn_cancel:
finish();
break;
case R.id.wifi_password:
InputMethodManager imm = (InputMethodManager)InputPwActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
break;
case R.id.wifi_check:
if(mCheckPw.isChecked()){
mCheckPw.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
} else {
mCheckPw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
}
break;
}
}
}
这是我试过比较好用的wifi连接~给大家分享。也给自己以后查询方便,有错误请大家指教。(●’◡’●)