android wifi操作(扫描和连接)

android系列wifi操作,首先应该添加如下权限:

    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
    </uses-permission>
首先写一个wifisevice,操作wifi

package com.example.androidwifi;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.IntentService;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
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.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class WifiService extends IntentService {

	private static final String DEBUG = "debug";
	private static List<ScanResult>resultList = new ArrayList<ScanResult>();
	private List<WifiConfiguration>wificonfigList = new ArrayList<WifiConfiguration>();
	private NetworkInfo mnetWorkInfo;
	private WifiInfo mWifiInfo;
	private WifiManager mwifiManager;//管理wifi

	public  List<Map<String,String>>mlist = new ArrayList<Map<String,String>>();

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		//获得系统wifi服务
		mwifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
		registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		int status = intent.getExtras().getInt("status");
		switch (status) {
		case 0://open wifi && search wifi
			Log.d(DEBUG, "打开service wifi");
			if (!mwifiManager.isWifiEnabled()) {
				mwifiManager.setWifiEnabled(true);
				resultList.clear();
				mwifiManager.startScan();//开始搜索,当搜索到可用的wifi时,将发送WifiManager.SCAN_RESULTS_AVAILABLE_ACTION的广播
				
				while (mlist.size() == 0) {//此处休眠0.1秒是因为搜索wifi是一个耗时的操作,如果不休眠,则扫描结果可能为空
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				Intent broadCastIntent = new Intent();
//				Bundle bundle = new Bundle();
				broadCastIntent.putExtra("result",(Serializable) mlist);

				broadCastIntent.setAction("com.androidwifi.opensuccess");
				sendBroadcast(broadCastIntent);

			}
			break;
		case 1://close wifi
			Log.d(DEBUG, "关闭service wifi");
			if (mwifiManager.isWifiEnabled()) {
				mwifiManager.setWifiEnabled(false);
			}
			break;
		case 2:
			int result = -1;//表示链接失败
			Intent resultIntent = new Intent(); 
			resultIntent.setAction("com.androidwifi.result");
			
			String  ssid= intent.getStringExtra("ssid");
			String pass = intent.getStringExtra("pass");
			
			resultIntent.putExtra("ssid",ssid);
			int netWorkId = AddWifiConfig(resultList, ssid, pass);//添加该网络的配置
			if (netWorkId !=-1) {
				getConfigurations();
				boolean isConnect = ConnectWifi(netWorkId);
				if (isConnect) {
					result = 1;
				}
			}
			resultIntent.putExtra("result",result);
			sendBroadcast(resultIntent);
			break;
			
		default:
			break;
		}

	}

	/**
	 * 当搜索到可用wifi时,将结果封装到mlist中
	 */
	private final BroadcastReceiver wifiReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context arg0, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
				resultList = mwifiManager.getScanResults();
				sortByLevel(resultList);
				for (ScanResult scanResult : resultList) {
					Map<String,String>map = new HashMap<String, String>();
					map.put("wifi_name",scanResult.SSID);
					map.put("wifi_bssid",scanResult.BSSID);
					mlist.add(map);
				}
			}

		}
	};

	/**
	 * 得到配置信息
	 */
	public void getConfigurations() {
		wificonfigList = mwifiManager.getConfiguredNetworks();
	}
	
	/**
	 * 该链接是否已经配置过
	 * @param SSID
	 * @return
	 */
	public int isConfigured(String SSID) {
		for (int i = 0; i < wificonfigList.size(); i++) {
			if (wificonfigList.get(i).SSID.equals(SSID)) {
				return wificonfigList.get(i).networkId;
			}
		}
		return -1;
	}
	/**
	 * 链接到制定wifi
	 * @param wifiId
	 * @return
	 */
	public boolean ConnectWifi(int wifiId){
		boolean isConnect = false;
		int id= 0;
		for(int i = 0; i < wificonfigList.size(); i++){
			WifiConfiguration wifi = wificonfigList.get(i);
			id = wifi.networkId;
			if(id == wifiId){
				while(!(mwifiManager.enableNetwork(wifiId, true))){
					Log.i("ConnectWifi",String.valueOf(wificonfigList.get(wifiId).status));
				}

				if ( mwifiManager.enableNetwork(wifiId, true)) {
					isConnect = true;
				}
			}
		}
		return isConnect;
	}
	
	/**
	 * 添加wifi配置
	 * @param wifiList
	 * @param ssid
	 * @param pwd
	 * @return
	 */
	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+"\"";
				wifiCong.hiddenSSID = false;
				wifiCong.status = WifiConfiguration.Status.ENABLED;
				wifiId = mwifiManager.addNetwork(wifiCong);
				if(wifiId != -1){
					return wifiId;
				}
			}
		}
		return wifiId;
	}
	
	//将搜索到的wifi根据信号强度从强到弱进行排序
	private void sortByLevel(List<ScanResult> resultList) {
		for(int i=0;i<resultList.size();i++)
			for(int j=1;j<resultList.size();j++)
			{
				if(resultList.get(i).level<resultList.get(j).level)    //level属性即为强度
				{
					ScanResult temp = null;
					temp = resultList.get(i);
					resultList.set(i, resultList.get(j));
					resultList.set(j, temp);
				}
			}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
	
		unregisterReceiver(wifiReceiver);
		super.onDestroy();
	}
	
	public WifiService() {
		super("");
		// TODO Auto-generated constructor stub
	}

}

mainactivity.java代码如下:

package com.example.androidwifi;

import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {

	private Button msearchBtn;
	private Button mopenBtn;
	private Button mcloseBtn;
	private static  ListView msearchList;
	private static ProgressDialog dialog;
	private static LinearLayout openView;
	static List<Map<String,String>>mlist;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		msearchList = (ListView) findViewById(R.id.resultlist);
		msearchList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View view, int position,
					long arg3) {
				// TODO Auto-generated method stub
				WifiService service = new WifiService();

				Map<String,String>map = mlist.get(position);//得到对应的list中的map
				final String ssid = map.get("wifi_name");//得到点击的热点的ssid,即wifi名称
				int wifiItemId = service.isConfigured("\""+ssid+"\"");//判断是否已经存储该热点的信息,返回bssid
				if (service.ConnectWifi(wifiItemId)) {
					view.setBackgroundResource(R.color.green);
				}else{//弹出对话框,输入密码

					View inflater = LayoutInflater.from(MainActivity.this).inflate(R.layout.ensure_conn,null);
					final AlertDialog alertDialog =new  AlertDialog.Builder(MainActivity.this).setTitle("请输入密码").setView(inflater).create();
					alertDialog.show();
					final EditText passEdit = (EditText) inflater.findViewById(R.id.pass);
					Button connBtn = (Button) inflater.findViewById(R.id.conn);
					connBtn.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							String pass = passEdit.getText().toString();
							if (null == pass || "".equals(pass)) {
								Toast.makeText(MainActivity.this,"请输入密码",1000).show();
								return;
							}
							Intent connectIntent = new Intent(MainActivity.this,WifiService.class);
							Bundle bundle = new Bundle();
							bundle.putInt("status",2);
							connectIntent.putExtras(bundle);
							connectIntent.putExtra("ssid",ssid);
							connectIntent.putExtra("pass",pass);
							startService(connectIntent);
							alertDialog.dismiss();
							dialog =ProgressDialog.show(MainActivity.this,"","正在链接"+ssid);

						}
					});
				}
			}
		});
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}



	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		@SuppressWarnings("unused")
		LayoutInflater inflater = LayoutInflater.from(this);
		switch (item.getItemId()) {
		case R.id.open_wifi://open wifi && search wifi
			Intent openWifiIntent = new Intent(MainActivity.this,WifiService.class);
			Bundle openBundle = new Bundle();
			openBundle.putInt("status",0);
			openWifiIntent.putExtras(openBundle);
			startService(openWifiIntent);

			dialog = ProgressDialog.show(this,"正在打开wifi","正在搜索wifi...");

			break;
		case R.id.close_wifi://close wifi

			Intent closeWifiIntent = new Intent(MainActivity.this,WifiService.class);
			Bundle closeBundle = new Bundle();
			closeBundle.putInt("status",1);
			closeWifiIntent.putExtras(closeBundle);
			startService(closeWifiIntent);
			break;
		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	public static class WifiReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals("com.androidwifi.opensuccess")) {
				@SuppressWarnings("unchecked")
				List<Map<String, String>>list = (List<Map<String, String>>) intent.getSerializableExtra("result");
				mlist = list;
				dialog.dismiss();
				//				ArrayAdapter<String>adapter = new ArrayAdapter<String>(context,android.R.layout.simple_list_item_1,scanResult);
				SimpleAdapter adapter = new SimpleAdapter(context, mlist, R.layout.searchlist_item,new String[]{"wifi_name","wifi_bssid"},new int[]{R.id.wifi_name,R.id.wifi_bssid});

				msearchList.setAdapter(adapter);

			}

		}

	}

	public static class WifiResultReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			// TODO Auto-generated method stub
			if (intent.getAction().equals("com.androidwifi.result")) {
				int result = intent.getIntExtra("result",0);
				String ssid = intent.getStringExtra("ssid");
				if (result == -1) {
					Toast.makeText(context,"链接"+ssid+"失败",1000).show();
				}
				if (result == 1) {
					Toast.makeText(context,"已链接到"+ssid,1000).show();
				}
			}
		}
	}

}

源码连接 http://download.csdn.net/detail/mockingbirds/8108345


你可能感兴趣的:(Android开发,layout,wifi)