先写一个主Activity 然后是一个工具类和一个dialog
xml很简单:两个:主页:<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
android:gravity="center_horizontal"
android:background="@color/burlywood"
tools:context=".ControlPCMainActivity" >
<Button
android:id="@+id/wifiSearchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="搜索WIFI信号"/>
<ListView
android:id="@+id/wifiListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cursorVisible="false"
android:singleLine="false"/>
</LinearLayout>
dialog:
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.Toast;
import com.wifi.utils.WifiPswDialog;
import com.wifi.utils.WifiPswDialog.OnCustomDialogListener;
import com.wifi.utils.WifiUtils;
public class ControlPCMainActivity extends Activity {
private String wifiPassword = null;
private Button wifiSearchButton;
private WifiUtils localWifiUtils;
private List<ScanResult> wifiResultList;
private List<String> wifiListString = new ArrayList<String>();
private ListView wifiSearchListView;
private ArrayAdapter<String> arrayWifiAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control_pcmain);
wifiSearchButton = (Button)findViewById(R.id.wifiSearchButton);
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);
ListOnItemClickListener wifiListListener = new ListOnItemClickListener();
wifiSearchListView.setOnItemClickListener(wifiListListener);
localWifiUtils = new WifiUtils(ControlPCMainActivity.this);
}
@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
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();
localWifiUtils.getConfiguration();
if(wifiListString != null){
Log.i("WIFIButtonListener","dataChange");
scanResultToString(wifiResultList,wifiListString);
}
}
}
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项背景设置
String wifiItem = arrayWifiAdapter.getItem(arg2);//获得选中的设备
String []ItemValue = wifiItem.split("--");
wifiItemSSID = ItemValue[0];
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.green);
}
}
else{//没有配置好信息,配置
WifiPswDialog pswDialog = new WifiPswDialog(ControlPCMainActivity.this,new OnCustomDialogListener() {
@Override
public void back(String str) {
// TODO Auto-generated method stub
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)){
selectedItem.setBackgroundResource(R.color.green);
}
}
else{
Toast.makeText(ControlPCMainActivity.this, "网络连接错误", Toast.LENGTH_SHORT).show();
selectedItem.setBackgroundResource(R.color.burlywood);
}
}
else{
selectedItem.setBackgroundResource(R.color.burlywood);
}
}
});
pswDialog.show();
}
}
}
//ScanResult类型转为String
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;
boolean bool = listStr.add(str);
if(bool){
arrayWifiAdapter.notifyDataSetChanged();//数据更新,只能单个Item更新,不能够整体List更新
}
else{
Log.i("scanResultToSting","fail");
}
Log.i("scanResultToString",listStr.get(i));
}
}
/*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);
}
}
}
}
};*/
}
工具类utils:WifiUtils 这个在wife中都可以用
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();
}
}
最后弹出输入密码的dialog:WifiPswDialog
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();
}
}
};
}