首页 > 系统 > Android > 正文

Android wifi搜索与连接

2019-11-08 00:23:48
字体:
来源:转载
供稿:网友
package com.wifi.utils;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.util.Log;public class 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 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;	}	//添加指定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();	}}

package com.wifi.utils;import android.app.Dialog;import android.content.Context;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import com.example.controlpcpro.R;public class WifiPswDialog extends Dialog{	private Button cancelButton;	private Button okButton;	private EditText pswEdit;	private OnCustomDialogListener customDialogListener;	public WifiPswDialog(Context context,OnCustomDialogListener customListener) {			//OnCancelListener cancelListener) {		super(context);		// TODO Auto-generated constructor stub		customDialogListener = customListener;			}	//定义dialog的回调事件	public interface OnCustomDialogListener{		void back(String str);	}	@Override	protected void onCreate(Bundle savedInstanceState) {		// TODO Auto-generated method stub		super.onCreate(savedInstanceState);		setContentView(R.layout.wifi_config_dialog);		setTitle("请输入密码");		pswEdit = (EditText)findViewById(R.id.wifiDialogPsw);		cancelButton = (Button)findViewById(R.id.wifiDialogCancel);		okButton = (Button)findViewById(R.id.wifiDialogCertain);		cancelButton.setOnClickListener(buttonDialogListener);		okButton.setOnClickListener(buttonDialogListener);			}		private View.OnClickListener buttonDialogListener = new View.OnClickListener() {		@Override		public void onClick(View view) {			// TODO Auto-generated method stub			if(view.getId() == R.id.wifiDialogCancel){				pswEdit = null;				customDialogListener.back(null);				cancel();//自动调用dismiss();			}			else{				customDialogListener.back(pswEdit.getText().toString());				dismiss();			}		}	};	}
package com.example.controlpcpro;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.os.Handler;import android.os.Message;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.LinearLayout;import android.widget.ProgressBar;import android.widget.TextView;public class WTAdapter extends BaseAdapter {	private LayoutInflater mInflater;	private List<ScanResult> mList;	private Context mContext;	public WTAdapter(Context context, List<ScanResult> list) {		// TODO Auto-generated constructor stub		this.mContext = context;		this.mList = list;		this.mInflater = LayoutInflater.from(context);	}	// 新加的一个函数,用来更新数据	public void setData(List<ScanResult> list) {		//Log.i("way", "mList length = "+list.size());		//mList.clear();		this.mList = list;		Log.i("way", "mList length = "+mList.size());		notifyDataSetChanged();	}	@Override	public int getCount() {		// TODO Auto-generated method stub		return mList.size();	}	@Override	public Object getItem(int position) {		// TODO Auto-generated method stub		return mList.get(position);	}	@Override	public long getItemId(int position) {		// TODO Auto-generated method stub		return position;	}	@Override	public View getView(final int position, View convertView, ViewGroup parent) {		// TODO Auto-generated method stub		final ScanResult localScanResult = mList.get(position);		//final WifiAdmin wifiAdmin = WifiAdmin.getInstance(mContext);		final ViewHolder viewHolder;		if (convertView == null) {			viewHolder = new ViewHolder();			convertView = mInflater.inflate(R.layout.wtitem, null);			viewHolder.textVName = ((TextView) convertView					.findViewById(R.id.name_text_wtitem));			viewHolder.textConnect = ((TextView) convertView					.findViewById(R.id.connect_text_wtitem));			viewHolder.linearLConnectOk = ((LinearLayout) convertView					.findViewById(R.id.connect_ok_layout_wtitem));			viewHolder.progressBConnecting = ((ProgressBar) convertView					.findViewById(R.id.connecting_progressBar_wtitem));			viewHolder.textVMac = ((TextView) convertView					.findViewById(R.id.name_text_mac));						viewHolder.textVJingwei = ((TextView) convertView					.findViewById(R.id.jingwei));			viewHolder.textVAddress = ((TextView) convertView					.findViewById(R.id.address));			convertView.setTag(viewHolder);		} else {			viewHolder = (ViewHolder) convertView.getTag();		}		// 点击连接处理事件		viewHolder.textConnect.setOnClickListener(new OnClickListener() {			@Override			public void onClick(View v) {				// TODO Auto-generated method stub				/*WifiConfiguration localWifiConfiguration = wifiAdmin						.createWifiInfo(localScanResult.SSID, WTActivity.WIFI_AP_PASSWORD, 3,								"wt");				wifiAdmin.addNetwork(localWifiConfiguration);				viewHolder.textConnect.setVisibility(View.GONE);				viewHolder.progressBConnecting.setVisibility(View.VISIBLE);				viewHolder.linearLConnectOk.setVisibility(View.GONE);				Handler localHandler = ((WTActivity) mContext).handler;				localHandler.sendEmptyMessageDelayed(						WTActivity.m_nWTConnected, 3500L);*/			}		});		// 点击断开处理事件		viewHolder.linearLConnectOk.setOnClickListener(new OnClickListener() {			@Override			public void onClick(View v) {				// TODO Auto-generated method stub				/*wifiAdmin						.disconnectWifi(wifiAdmin.getWifiInfo().getNetworkId());				viewHolder.textConnect.setVisibility(View.GONE);				viewHolder.progressBConnecting.setVisibility(View.VISIBLE);				viewHolder.linearLConnectOk.setVisibility(View.GONE);				Handler localHandler = ((WTActivity) mContext).handler;				localHandler.sendEmptyMessageDelayed(						WTActivity.m_nWTConnected, 3500L);*/			}		});		viewHolder.textConnect.setVisibility(View.GONE);		viewHolder.progressBConnecting.setVisibility(View.GONE);		viewHolder.linearLConnectOk.setVisibility(View.GONE);		viewHolder.textVName.setText("SSID:"+localScanResult.SSID);		viewHolder.textVMac.setText("MAC:"+localScanResult.BSSID);		if(Locationapplication.location != null){			viewHolder.textVJingwei.setText("纬度"+LocationApplication.location.getLatitude()+";经度"+LocationApplication.location.getLongitude());			viewHolder.textVAddress.setText("address:"+LocationApplication.location.getAddrStr());		}				/*WifiInfo localWifiInfo = WifiAdmin.getInstance(mContext).getWifiInfo();// 正连接的wifi信息		if (localWifiInfo != null) {			try {				if ((localWifiInfo.getSSID() != null)						&& (localWifiInfo.getSSID()								.equals(localScanResult.SSID))) {					viewHolder.linearLConnectOk.setVisibility(View.VISIBLE);					return convertView;				}			} catch (NullPointerException localNullPointerException) {				localNullPointerException.printStackTrace();				return convertView;			}			viewHolder.textConnect.setVisibility(View.VISIBLE);		}*/		return convertView;	}	public final class ViewHolder {		public LinearLayout linearLConnectOk;		public ProgressBar progressBConnecting;		public TextView textConnect;		public TextView textVName;		public TextView textVMac;				public TextView textVJingwei;		public TextView textVAddress;				public ViewHolder() {		}	}}
package com.example.controlpcpro;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.net.wifi.ScanResult;import android.net.wifi.WifiManager;import android.os.Bundle;import android.util.Log;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.ListView;import android.widget.TextView;import android.widget.Toast;import com.baidu.location.LocationClient;import com.baidu.location.LocationClientOption;import com.baidu.location.LocationClientOption.LocationMode;import com.wifi.utils.WifiPswDialog;import com.wifi.utils.WifiPswDialog.OnCustomDialogListener;import com.wifi.utils.WifiUtils;public class WTActivity extends Activity {	private String wifiPassword = null;	private Button wifiSearchButton, backButton;	private WifiUtils localWifiUtils;	private List<ScanResult> wifiResultList;	private List<String> wifiListString = new ArrayList<String>();	private ListView wifiSearchListView;	//private ArrayAdapter<String> arrayWifiAdapter;	private WTAdapter wtAdapter;		private LocationClient mLocationClient;//定位SDK的核心类	private TextView LocationResult;		@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.activity_control_pcmain);		LocationResult = (TextView)findViewById(R.id.tv_loc_info);		mLocationClient = ((LocationApplication)getApplication()).mLocationClient;		((LocationApplication)getApplication()).mLocationResult = LocationResult;//调用LocationApplication,获得需要的信息				mLocationClient.stop();		mLocationClient.start();				wifiSearchButton = (Button)findViewById(R.id.search_btn_wt_main);		backButton = (Button)findViewById(R.id.back_btn_wt_main);		backButton.setOnClickListener(new OnClickListener() {						@Override			public void onClick(View arg0) {				// TODO Auto-generated method stub				WTActivity.this.finish();			}		});		WIFIButtonListener wifiButtonListener = new WIFIButtonListener();		wifiSearchButton.setOnClickListener(wifiButtonListener);		wifiSearchListView = (ListView)findViewById(R.id.wifiListView);				//arrayWifiAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,wifiListString);		//wifiSearchListView.setAdapter(arrayWifiAdapter);				wifiResultList = new ArrayList<ScanResult>();		wtAdapter = new WTAdapter(this, wifiResultList);		wifiSearchListView.setAdapter(wtAdapter);				ListOnItemClickListener wifiListListener = new ListOnItemClickListener();		wifiSearchListView.setOnItemClickListener(wifiListListener);				localWifiUtils = new WifiUtils(WTActivity.this);	}	        private Button startLocation;	/*@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.main);        mLocationClient = ((LocationApplication)getApplication()).mLocationClient;                 LocationResult = (TextView)findViewById(R.id.tv_loc_info);         ((LocationApplication)getApplication()).mLocationResult = LocationResult;//调用LocationApplication,获得需要的信息        startLocation = (Button)findViewById(R.id.btn_start);        startLocation.setOnClickListener(new OnClickListener() {                         public void onClick(View v) {                InitLocation();//初始化                if(startLocation.getText().equals("开启定位")){                    mLocationClient.start();                    startLocation.setText("停止定位");                }else{                    mLocationClient.stop();                    startLocation.setText("开启定位");                }            }        });	}*/		 private void InitLocation(){	        LocationClientOption option = new LocationClientOption();	        option.setLocationMode(LocationMode.Hight_Accuracy);//设置高精度定位定位模式	        option.setCoorType("bd09ll");//设置百度经纬度坐标系格式	        option.setScanSpan(1000);//设置发起定位请求的间隔时间为1000ms	        option.setIsNeedAddress(true);//反编译获得具体位置,只有网络定位才可以	        mLocationClient.setLocOption(option);	    }	 @Override	    protected void onStop() {	        mLocationClient.stop();	        super.onStop();	    }	 	@Override	public boolean onCreateOptionsMenu(Menu menu) {		// Inflate the menu; this adds items to the action bar if it is present.		getMenuInflater().inflate(R.menu.control_pcmain, menu);		return true;	}		class WIFIButtonListener implements OnClickListener{		@Override		public void onClick(View view) {			// TODO Auto-generated method stub			mLocationClient.stop();			mLocationClient.start();			wifiListString.clear();			localWifiUtils.WifiOpen();			localWifiUtils.WifiStartScan();			//0正在关闭,1WIFi不可用,2正在打开,3可用,4状态不可zhi			while(localWifiUtils.WifiCheckState() != WifiManager.WIFI_STATE_ENABLED){//等待Wifi开启				Log.i("WifiState",String.valueOf(localWifiUtils.WifiCheckState()));			}			try {					Thread.sleep(3000);//休眠3s,不休眠则会在程序首次开启WIFI时候,处理getScanResults结果,wifiResultList.size()发生异常				} catch (InterruptedException e) {					// TODO Auto-generated catch block					e.printStackTrace();				}			wifiResultList = localWifiUtils.getScanResults();			System.out.println("++++++++++"+wifiResultList.size());			localWifiUtils.getConfiguration();			if(wifiListString != null){				Log.i("WIFIButtonListener","dataChange");				scanResultToString(wifiResultList,wifiListString);			}		}	}		public void scanResultToString(List<ScanResult> listScan,List<String> listStr){		for(int i = 0; i <listScan.size(); i++){			ScanResult strScan = listScan.get(i);			String str = strScan.SSID+"--"+strScan.BSSID;			//String str = strScan.			boolean bool = listStr.add(str);			if(bool){				//wtAdapter.notifyDataSetChanged();//数据更新,只能单个Item更新,不能够整体List更新				wtAdapter = new WTAdapter(this, wifiResultList);				wifiSearchListView.setAdapter(wtAdapter);			}			else{				Log.i("scanResultToSting","fail");			}			Log.i("scanResultToString",listStr.get(i));		}	}		class ListOnItemClickListener implements OnItemClickListener{		String wifiItemSSID = null;		private View selectedItem;		@Override		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,				long arg3) {			// TODO Auto-generated method stub			Log.i("ListOnItemClickListener","start");			selectedItem = arg1;			//arg1.setBackgroundResource(R.color.gray);//点击的Item项背景设置			ScanResult wifiItem = wifiResultList.get(arg2);//获得选中的设备						wifiItemSSID = wifiItem.SSID; 			Log.i("ListOnItemClickListener",wifiItemSSID);			int wifiItemId = localWifiUtils.IsConfiguration("/""+wifiItemSSID+"/"");			Log.i("ListOnItemClickListener",String.valueOf(wifiItemId));			if(wifiItemId != -1){				if(localWifiUtils.ConnectWifi(wifiItemId)){//连接指定WIFI					//arg1.setBackgroundResource(R.color.gray);					Toast.makeText(WTActivity.this, "已经连接该wifi", 1000).show();				}			}			else{//没有配置好信息,配置				Toast.makeText(WTActivity.this, "未连接该wifi", 1000).show();				/*WifiPswDialog pswDialog = new WifiPswDialog(WTActivity.this,new OnCustomDialogListener() {					@Override					public void back(String str) {						// TODO Auto-generated method stub						Toast.makeText(WTActivity.this, "未连接该wifi", 1000).show();						wifiPassword = str;						if(wifiPassword != null){							int netId = localWifiUtils.AddWifiConfig(wifiResultList,wifiItemSSID, wifiPassword);							Log.i("WifiPswDialog",String.valueOf(netId));							if(netId != -1){								localWifiUtils.getConfiguration();//添加了配置信息,要重新得到配置信息								if(localWifiUtils.ConnectWifi(netId)){																	}							}							else{								Toast.makeText(WTActivity.this, "网络连接错误", Toast.LENGTH_SHORT).show();								//selectedItem.setBackgroundResource(R.color.blue);							}						}						else{							//selectedItem.setBackgroundResource(R.color.blue);						}					}				});				pswDialog.show();*/			}		}	}	//ScanResult类型转为String		/*private BroadcastReceiver WifiBroadcastRec = new BroadcastReceiver(){	@Override	public void onReceive(Context context, Intent intent) {		// TODO Auto-generated method stub		String wifiAction = intent.getAction();		if(WifiManager.WIFI_STATE_CHANGED_ACTION.equals(wifiAction)){			int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,WifiManager.WIFI_STATE_ENABLED);			if(wifiState == WifiManager.WIFI_STATE_ENABLED){				try {					Thread.sleep(3000);//休眠3s,不休眠则会在程序首次开启WIFI时候,处理getScanResults结果,wifiResultList.size()发生异常				} catch (InterruptedException e) {					// TODO Auto-generated catch block					e.printStackTrace();				}				wifiResultList = localWifiUtils.getScanResults();				localWifiUtils.getConfiguration();				if(wifiListString != null){					scanResultToString(wifiResultList,wifiListString);				}			}		}  	  }	};*/		/*@Override	protected void onDestroy () {		super.onDestroy();		System.out.println("----------");		WTActivity.this.finish();	}*/}
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.controlpcpro"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="10"        android:targetSdkVersion="19" />	<!-- <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"></uses-permission>允许程序改变网络链接状态	<uses-permission android:name="android.permission.access_WIFI_STATE"></uses-permission>允许程序访问访问WIFI网络状态信息 	<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>允许程序改变WIFI链接状态	<uses-permission android:name="android.permission.INTERNET"></uses-permission>	 -->        <permission android:name="android.permission.BAIDU_LOCATION_SERVICE" >    </permission>     <uses-permission android:name="android.permission.BAIDU_LOCATION_SERVICE" >    </uses-permission>    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" >    </uses-permission>    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" >    </uses-permission>    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.READ_PHONE_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >    </uses-permission>    <uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" >    </uses-permission>    <uses-permission android:name="android.permission.READ_LOGS" >    </uses-permission>            <application        android:name="com.example.controlpcpro.LocationApplication"        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@android:style/Theme.NoTitleBar"  >        <activity            android:name="com.example.controlpcpro.WTActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity            android:name="com.example.controlpcpro.ControlActivity">        </activity>                        <meta-data  android:name="com.baidu.lbsapi.API_KEY"  android:value="ksgmo1pQZVALFzdo1OgiAaXD" />            </application></manifest>


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表