[置顶] Android之高仿飞鸽传输热点创建与搜索模块

这两天,无意中看到飞鸽传书的wifi热点创建与搜索模块,于是乎很蛋疼的还原了一下他的这一小模块代码,感觉效果差不多,跟大家分享一下:

源码下载地址:http://download.csdn.net/download/weidi1989/5293352


我们先来看看效果图:

1.山寨机主界面

2.进应用就会自动搜索wifi,这个动画效果截屏变形了。将就一下吧

3.搜索结果显示

4.连接上我另外一台山寨机创建的热点

5.正在创建热点

6.热点创建成功,关于那个黑黑的gif动画,我试了三种方法:①.网上导了那个很泛滥的包,不行,②.用Movie实现的动画,还是不行,在有的机器上会花屏,③.就是下面这个效果了,自定义的一个view,由于图片是透明的,所以黑色底没有解决。

[置顶] Android之高仿飞鸽传输热点创建与搜索模块_第1张图片  [置顶] Android之高仿飞鸽传输热点创建与搜索模块_第2张图片  [置顶] Android之高仿飞鸽传输热点创建与搜索模块_第3张图片  [置顶] Android之高仿飞鸽传输热点创建与搜索模块_第4张图片  [置顶] Android之高仿飞鸽传输热点创建与搜索模块_第5张图片  [置顶] Android之高仿飞鸽传输热点创建与搜索模块_第6张图片

下面是几个关键类的代码:

1.我们先来看看这个广播:WTBroadcast,通过这个广播,可以及时更新我们的界面显示信息。重点是“android.net.wifi.WIFI_STATE_CHANGED” 与“android.net.wifi.STATE_CHANGE”两个状态的区别

/**
 * wifi状态监听广播
 * 
 * @author way
 * 
 */
public class WTBroadcast extends BroadcastReceiver {
	public static ArrayList<EventHandler> ehList = new ArrayList();

	public void onReceive(Context paramContext, Intent paramIntent) {
		if (paramIntent.getAction().equals("android.net.wifi.SCAN_RESULTS")) {
			// 搜索到wifi热点结果广播
			Log.i("WTScanResults", "android.net.wifi.SCAN_RESULTS");
			// 遍历通知各个监听接口
			for (int j = 0; j < ehList.size(); j++)
				((EventHandler) ehList.get(j)).scanResultsAvailable();
		} else if (paramIntent.getAction().equals(
				"android.net.wifi.WIFI_STATE_CHANGED")) {
			// wifi打开或关闭广播(不需要连接上一个SSID)
			Log.e("WTScanResults", "android.net.wifi.WIFI_STATE_CHANGED");
			for (int j = 0; j < ehList.size(); j++)
				((EventHandler) ehList.get(j)).wifiStatusNotification();
		} else if (paramIntent.getAction().equals(
				"android.net.wifi.STATE_CHANGE")) {
			// 连接上一个SSID后发出的广播,与android.net.wifi.WIFI_STATE_CHANGED有一定区别
			Log.e("WTScanResults", "android.net.wifi.STATE_CHANGE");
			for (int i = 0; i < ehList.size(); i++)
				((EventHandler) ehList.get(i)).handleConnectChange();
		}
	}

	/**
	 * 用来更新的接口
	 * 
	 * @author way
	 * 
	 */
	public static abstract interface EventHandler {
		public abstract void handleConnectChange();

		public abstract void scanResultsAvailable();

		public abstract void wifiStatusNotification();
	}
}


2.接下来是主Activity了:WTActivity,在这个Activity中,我们来处理各种界面事件,同时根据wifi状态变化,动态更新界面,值得学习的是自定义view和handler事件处理,还有超时线程的理论。内容比较多,我把它综合到一个类中,其实可以把一些常用的函数放在Application类中。

/**
 * 主Activity
 * 
 * @author way
 * 
 */
public class WTActivity extends Activity implements WTBroadcast.EventHandler {
	public static final int m_nWTSearchTimeOut = 0;// 搜索超时
	public static final int m_nWTScanResult = 1;// 搜索到wifi返回结果
	public static final int m_nWTConnectResult = 2;// 连接上wifi热点
	public static final int m_nCreateAPResult = 3;// 创建热点结果
	public static final int m_nUserResult = 4;// 用户上线人数更新命令(待定)
	public static final int m_nWTConnected = 5;// 点击连接后断开wifi,3.5秒后刷新adapter
	public static final String PACKAGE_NAME = "com.way.wifi";
	public static final String FIRST_OPEN_KEY = "version";
	public static final String WIFI_AP_HEADER = "way_";
	public static final String WIFI_AP_PASSWORD = "way12345";

	private WTSearchAnimationFrameLayout m_FrameLWTSearchAnimation;
	private LinearLayout m_LinearLDialog;
	private LinearLayout m_LinearLIntroduction;
	private Button m_btnBack;
	private Button m_btnCancelDialog;
	private Button m_btnConfirmDialog;
	private Button m_btnCreateWT;
	private Button m_btnSearchWT;
	private GifView m_gifRadar;
	private boolean m_isFirstOpen = true;
	private LinearLayout m_linearLCreateAP;
	private ListView m_listVWT;
	ArrayList<ScanResult> m_listWifi = new ArrayList();
	private ProgressBar m_progBarCreatingAP;
	private TextView m_textVContentDialog;
	private TextView m_textVPromptAP;
	private TextView m_textVWTPrompt;
	private WifiAdmin m_wiFiAdmin;
	private CreateAPProcess m_createAPProcess;
	private WTSearchProcess m_wtSearchProcess;
	private int wTOperateEnum = WTOperateEnum.NOTHING;
	private WTAdapter m_wTAdapter;

	public Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case m_nWTSearchTimeOut://wifi搜索超时处理
				m_wtSearchProcess.stop();
				m_FrameLWTSearchAnimation.stopAnimation();
				m_listWifi.clear();
				m_textVWTPrompt.setVisibility(View.VISIBLE);
				m_textVWTPrompt.setText(R.string.wt_list_empty);
				break;
			case m_nWTScanResult://搜索到可连接wifi
				m_listWifi.clear();
				int size = m_wiFiAdmin.mWifiManager.getScanResults().size();
				if (size > 0) {
					for (int i = 0; i < size; ++i) {
						ScanResult scanResult = m_wiFiAdmin.mWifiManager
								.getScanResults().get(i);
						// Log.i("way", "SSID = " + scanResult.SSID);
						if (scanResult.SSID.startsWith(WIFI_AP_HEADER)) {
							m_listWifi.add(scanResult);
						}
					}
					if (m_listWifi.size() > 0) {
						m_wtSearchProcess.stop();
						m_FrameLWTSearchAnimation.stopAnimation();
						m_textVWTPrompt.setVisibility(View.GONE);
						m_wTAdapter.setData(m_listWifi);
						m_wTAdapter.notifyDataSetChanged();
					}
				}
				break;
			case m_nWTConnectResult://连接上一个热点更新一下状态
				m_wTAdapter.notifyDataSetChanged();
				break;
			case m_nCreateAPResult://创建热点结果
				m_createAPProcess.stop();
				m_progBarCreatingAP.setVisibility(View.GONE);
				if (((m_wiFiAdmin.getWifiApState() == 3) || (m_wiFiAdmin
						.getWifiApState() == 13))
						&& (m_wiFiAdmin.getApSSID().startsWith(WIFI_AP_HEADER))) {
					m_textVWTPrompt.setVisibility(View.GONE);
					m_linearLCreateAP.setVisibility(View.VISIBLE);
					m_btnCreateWT.setVisibility(View.VISIBLE);
					m_gifRadar.setVisibility(View.VISIBLE);
					m_btnCreateWT.setBackgroundResource(R.drawable.x_ap_close);
					m_textVPromptAP
							.setText(getString(R.string.pre_wt_connect_ok)
									+ getString(R.string.middle_wt_connect_ok)
									+ m_wiFiAdmin.getApSSID()
									+ getString(R.string.suf_wt_connect_ok));
				} else {
					m_btnCreateWT.setVisibility(View.VISIBLE);
					m_btnCreateWT.setBackgroundResource(R.drawable.x_wt_create);
					m_textVPromptAP.setText(R.string.create_ap_fail);
				}
				break;
			case m_nUserResult:
				// 更新用户上线人数,待定
				break;
			case m_nWTConnected://点击连接热点超时处理
				m_wTAdapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
		}
	};
	
	/**
	 * 获取共享热点状态
	 * @return 是否开启共享
	 */
	public boolean getWifiApState() {
		try {
			WifiManager localWifiManager = (WifiManager) getSystemService("wifi");
			int i = ((Integer) localWifiManager.getClass()
					.getMethod("getWifiApState", new Class[0])
					.invoke(localWifiManager, new Object[0])).intValue();
			return (3 == i) || (13 == i);
		} catch (Exception localException) {
		}
		return false;
	}
	/**
	 * 是否连接上wifi
	 * @return
	 */
	public boolean isWifiConnect() {
		boolean isConnect = true;
		if (!((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected())
			isConnect = false;
		return isConnect;
	}

	/**
	 *  是否为第一次打开应用,根据版本判断会比较好,因为商业应用会执行自动更新,
	 * @return
	 */
	private boolean isFirstOpen() {
		try {
			PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME,
					0);
			int currentVersion = info.versionCode;
			SharedPreferences prefs = PreferenceManager
					.getDefaultSharedPreferences(this);
			int lastVersion = prefs.getInt(FIRST_OPEN_KEY, 0);
			if (currentVersion > lastVersion) {
				prefs.edit().putInt(FIRST_OPEN_KEY, currentVersion).commit();
				return true;
			}
		} catch (PackageManager.NameNotFoundException e) {
			Log.w("way", e);
		}
		return false;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wt_main);
		m_wtSearchProcess = new WTSearchProcess();
		m_createAPProcess = new CreateAPProcess();
		m_wiFiAdmin = WifiAdmin.getInstance(this);
		initView();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (!m_isFirstOpen)
			init();//如果不是第一次打开应用,就执行更新
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		WTBroadcast.ehList.remove(this);
	}

	// 初始化view
	private void initView() {
		m_isFirstOpen = isFirstOpen();//是否第一次开启应用
		m_LinearLIntroduction = ((LinearLayout) findViewById(R.id.introduction_layout_wt_main));// 介绍使用的view
		m_LinearLIntroduction.setOnClickListener(new OnClickListener() {
			public void onClick(View paramView) {
				m_LinearLIntroduction.setVisibility(View.GONE);
				init();
			}

		});

		m_btnBack = ((Button) findViewById(R.id.back_btn_wt_main));// 返回键
		m_btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});

		m_linearLCreateAP = ((LinearLayout) findViewById(R.id.create_ap_llayout_wt_main));// 创建热点的view
		m_progBarCreatingAP = ((ProgressBar) findViewById(R.id.creating_progressBar_wt_main));// 创建热点的进度条
		m_textVPromptAP = ((TextView) findViewById(R.id.prompt_ap_text_wt_main));//创建热点的那个提醒textView
		m_btnSearchWT = ((Button) findViewById(R.id.search_btn_wt_main));// 搜索热点按钮
		m_btnSearchWT.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (!m_wtSearchProcess.running) {// 如果搜索线程没有启动
					if (m_wiFiAdmin.getWifiApState() == 13
							|| m_wiFiAdmin.getWifiApState() == 3) {
						wTOperateEnum = WTOperateEnum.SEARCH;
						m_LinearLDialog.setVisibility(View.VISIBLE);
						m_textVContentDialog.setText(R.string.opened_ap_prompt);
						return;
					}
					if (!m_wiFiAdmin.mWifiManager.isWifiEnabled()) {// 如果wifi打开着的
						m_wiFiAdmin.OpenWifi();
					}
					m_textVWTPrompt.setVisibility(View.VISIBLE);
					m_textVWTPrompt.setText(R.string.wt_searching);
					m_linearLCreateAP.setVisibility(View.GONE);
					m_gifRadar.setVisibility(View.GONE);
					m_btnCreateWT.setBackgroundResource(R.drawable.x_wt_create);
					m_wiFiAdmin.startScan();
					m_wtSearchProcess.start();
					m_FrameLWTSearchAnimation.startAnimation();
				} else {
					// 重新启动一下或者干脆return掉
					m_wtSearchProcess.stop();
					m_wiFiAdmin.startScan();
					m_wtSearchProcess.start();
				}
			}
		});
		m_btnCreateWT = ((Button) findViewById(R.id.create_btn_wt_main));// 创建热点的按钮
		m_btnCreateWT.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (m_wiFiAdmin.getWifiApState() == 4) {//如果不支持热点创建
					Toast.makeText(getApplicationContext(),
							R.string.not_create_ap, Toast.LENGTH_SHORT).show();
					return;
				}
				if (m_wiFiAdmin.mWifiManager.isWifiEnabled()) {//如果wifi正打开着的,就提醒用户
					wTOperateEnum = WTOperateEnum.CREATE;
					m_LinearLDialog.setVisibility(View.VISIBLE);
					m_textVContentDialog.setText(R.string.close_wifi_prompt);
					return;
				}

				if (((m_wiFiAdmin.getWifiApState() == 3) || (m_wiFiAdmin
						.getWifiApState() == 13))
						&& (!m_wiFiAdmin.getApSSID().startsWith(WIFI_AP_HEADER))) {//如果已经存在一个其他的共享热点
					wTOperateEnum = WTOperateEnum.CREATE;
					m_LinearLDialog.setVisibility(View.VISIBLE);
					m_textVContentDialog.setText(R.string.ap_used);
					return;
				}
				if (((m_wiFiAdmin.getWifiApState() == 3) || (m_wiFiAdmin
						.getWifiApState() == 13))
						&& (m_wiFiAdmin.getApSSID().startsWith(WIFI_AP_HEADER))) {//如果存在一个同名的共享热点
					wTOperateEnum = WTOperateEnum.CLOSE;
					m_LinearLDialog.setVisibility(View.VISIBLE);
					m_textVContentDialog.setText(R.string.close_ap_prompt);
					return;
				}
				if (m_wtSearchProcess.running) {//如果正在搜索状态
					m_wtSearchProcess.stop();
					m_FrameLWTSearchAnimation.stopAnimation();
				}
				m_wiFiAdmin.closeWifi();
				m_wiFiAdmin.createWiFiAP(m_wiFiAdmin.createWifiInfo(
						WIFI_AP_HEADER + getLocalHostName(), WIFI_AP_PASSWORD,
						3, "ap"), true);
				m_createAPProcess.start();
				m_listWifi.clear();
				m_wTAdapter.setData(m_listWifi);
				m_wTAdapter.notifyDataSetChanged();
				m_linearLCreateAP.setVisibility(View.VISIBLE);
				m_progBarCreatingAP.setVisibility(View.VISIBLE);
				m_btnCreateWT.setVisibility(View.GONE);
				m_textVWTPrompt.setVisibility(View.GONE);
				m_textVPromptAP.setText(getString(R.string.creating_ap));
			}
		});
		m_FrameLWTSearchAnimation = ((WTSearchAnimationFrameLayout) findViewById(R.id.search_animation_wt_main));// 搜索时的动画
		m_listVWT = ((ListView) findViewById(R.id.wt_list_wt_main));// 搜索到的热点listView
		m_wTAdapter = new WTAdapter(this, m_listWifi);
		m_listVWT.setAdapter(m_wTAdapter);

		m_textVWTPrompt = (TextView) findViewById(R.id.wt_prompt_wt_main);//搜索时提醒的textView
		m_gifRadar = (GifView) findViewById(R.id.radar_gif_wt_main);//创建热点后的gif动画View

		m_LinearLDialog = (LinearLayout) findViewById(R.id.dialog_layout_wt_main);//与用户交互的对话框
		m_textVContentDialog = (TextView) findViewById(R.id.content_text_wtdialog);
		m_btnConfirmDialog = (Button) findViewById(R.id.confirm_btn_wtdialog);
		m_btnCancelDialog = (Button) findViewById(R.id.cancel_btn_wtdialog);
		// 弹出对话框的确认按钮事件
		m_btnConfirmDialog.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				m_LinearLDialog.setVisibility(View.GONE);
				switch (wTOperateEnum) {
				case WTOperateEnum.CLOSE://如果是执行关闭热点事件
					m_textVWTPrompt.setVisibility(View.VISIBLE);
					m_textVWTPrompt.setText("");
					m_linearLCreateAP.setVisibility(View.GONE);
					m_btnCreateWT.setBackgroundResource(R.drawable.x_wt_create);
					m_gifRadar.setVisibility(View.GONE);
					m_wiFiAdmin.createWiFiAP(m_wiFiAdmin.createWifiInfo(
							m_wiFiAdmin.getApSSID(), "81028066", 3, "ap"),
							false);

					m_wiFiAdmin.OpenWifi();//关闭热点后重新开启一下wifi
					m_wtSearchProcess.start();
					m_wiFiAdmin.startScan();
					m_FrameLWTSearchAnimation.startAnimation();
					m_textVWTPrompt.setVisibility(View.VISIBLE);
					m_textVWTPrompt.setText(R.string.wt_searching);
					m_linearLCreateAP.setVisibility(View.GONE);
					m_btnCreateWT.setBackgroundResource(R.drawable.x_wt_create);
					break;
				case WTOperateEnum.CREATE://如果是执行创建热点事件
					if (m_wtSearchProcess.running) {
						m_wtSearchProcess.stop();
						m_FrameLWTSearchAnimation.stopAnimation();
					}
					m_wiFiAdmin.closeWifi();
					m_wiFiAdmin.createWiFiAP(m_wiFiAdmin.createWifiInfo(
							WIFI_AP_HEADER + getLocalHostName(),
							WIFI_AP_PASSWORD, 3, "ap"), true);
					m_createAPProcess.start();
					m_listWifi.clear();
					m_wTAdapter.setData(m_listWifi);
					m_wTAdapter.notifyDataSetChanged();
					m_linearLCreateAP.setVisibility(View.VISIBLE);
					m_progBarCreatingAP.setVisibility(View.VISIBLE);
					m_btnCreateWT.setVisibility(View.GONE);
					m_textVWTPrompt.setVisibility(View.GONE);
					m_textVPromptAP.setText(getString(R.string.creating_ap));
					break;
				case WTOperateEnum.SEARCH://如果是执行搜索wifi事件
					m_textVWTPrompt.setVisibility(View.VISIBLE);
					m_textVWTPrompt.setText(R.string.wt_searching);
					m_linearLCreateAP.setVisibility(View.GONE);
					m_btnCreateWT.setVisibility(View.VISIBLE);
					m_btnCreateWT.setBackgroundResource(R.drawable.x_wt_create);
					m_gifRadar.setVisibility(View.GONE);
					if (m_createAPProcess.running)
						m_createAPProcess.stop();
					m_wiFiAdmin.createWiFiAP(
							m_wiFiAdmin.createWifiInfo(m_wiFiAdmin.getApSSID(),
									WIFI_AP_PASSWORD, 3, "ap"), false);
					m_wiFiAdmin.OpenWifi();
					m_wtSearchProcess.start();
					m_FrameLWTSearchAnimation.startAnimation();
					break;
				default:
					break;
				}

			}
		});
		// 弹出对话框取消按钮事件
		m_btnCancelDialog.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				m_LinearLDialog.setVisibility(View.GONE);
			}
		});

		WTBroadcast.ehList.add(this);// 注意监听广播,
		if (m_isFirstOpen)//如果是第一次开启应用,打开帮助提示
			m_LinearLIntroduction.setVisibility(View.VISIBLE);
	}
	
	/**
	 * 获取手机信息
	 * @return
	 */
	public String getLocalHostName() {
		String str1 = Build.BRAND;
		String str2 = Build.MODEL;
		if (-1 == str2.toUpperCase().indexOf(str1.toUpperCase()))
			str2 = str1 + "_" + str2;
		return str2;
	}

	/**
	 *  初始化
	 */
	private void init() {
		// TODO Auto-generated method stub
		if ((this.m_wtSearchProcess.running)
				|| (this.m_createAPProcess.running))
			return;
		//只有以下三种情况
		if (!isWifiConnect() && !getWifiApState()) {//没有创建热点也没有打开wifi
			m_wiFiAdmin.OpenWifi();
			m_wtSearchProcess.start();
			m_wiFiAdmin.startScan();
			m_FrameLWTSearchAnimation.startAnimation();
			m_textVWTPrompt.setVisibility(View.VISIBLE);
			m_textVWTPrompt.setText(R.string.wt_searching);
			m_linearLCreateAP.setVisibility(View.GONE);
			m_btnCreateWT.setBackgroundResource(R.drawable.x_wt_create);
		}
		if (isWifiConnect()) {//如果打开了wifi
			this.m_wiFiAdmin.startScan();
			this.m_wtSearchProcess.start();
			this.m_FrameLWTSearchAnimation.startAnimation();
			this.m_textVWTPrompt.setVisibility(0);
			this.m_textVWTPrompt.setText(R.string.wt_searching);
			this.m_linearLCreateAP.setVisibility(8);
			this.m_btnCreateWT.setBackgroundResource(R.drawable.x_wt_create);
			this.m_gifRadar.setVisibility(8);
			m_listWifi.clear();
			if (m_wiFiAdmin.mWifiManager.getScanResults() != null) {
				int result = m_wiFiAdmin.mWifiManager.getScanResults().size();
				int i = 0;
				for (i = 0; i < result; ++i) {
					if (m_wiFiAdmin.mWifiManager.getScanResults().get(i).SSID
							.startsWith(WIFI_AP_HEADER))
						m_listWifi.add(m_wiFiAdmin.mWifiManager
								.getScanResults().get(i));
				}
				Log.i("way", "wifi size:"
						+ m_wiFiAdmin.mWifiManager.getScanResults().size());
			}
			m_wTAdapter.setData(m_listWifi);
			m_wTAdapter.notifyDataSetChanged();

		}

		if (getWifiApState()) {//如果创建了热点
			if (m_wiFiAdmin.getApSSID().startsWith(WIFI_AP_HEADER)) {
				m_textVWTPrompt.setVisibility(View.GONE);
				m_linearLCreateAP.setVisibility(View.VISIBLE);
				m_progBarCreatingAP.setVisibility(View.GONE);
				m_btnCreateWT.setVisibility(View.VISIBLE);
				m_gifRadar.setVisibility(View.VISIBLE);
				m_btnCreateWT.setBackgroundResource(R.drawable.x_ap_close);
				m_textVPromptAP.setText(getString(R.string.pre_wt_connect_ok)
						+ getString(R.string.middle_wt_connect_ok)
						+ m_wiFiAdmin.getApSSID()
						+ getString(R.string.suf_wt_connect_ok));
			}
		}
	}

	@Override
	public void handleConnectChange() {//监听广播,如果连接上一个热点,执行更新界面
		// TODO Auto-generated method stub
		Message msg = handler.obtainMessage(m_nWTConnectResult);
		handler.sendMessage(msg);
	}

	@Override
	public void scanResultsAvailable() {//监听广播,搜索到各个wifi
		// TODO Auto-generated method stub
		Message msg = handler.obtainMessage(m_nWTScanResult);
		handler.sendMessage(msg);
	}

	@Override
	public void wifiStatusNotification() {//监听打开或关闭wifi广播
		// TODO Auto-generated method stub
		m_wiFiAdmin.mWifiManager.getWifiState();
	}

	//创建热点进程与超时处理
	class CreateAPProcess implements Runnable {
		public boolean running = false;
		private long startTime = 0L;
		private Thread thread = null;

		CreateAPProcess() {
		}

		public void run() {
			while (true) {
				if (!this.running)
					return;
				if ((m_wiFiAdmin.getWifiApState() == 3)
						|| (m_wiFiAdmin.getWifiApState() == 13)
						|| (System.currentTimeMillis() - this.startTime >= 30000L)) {
					Message msg = handler.obtainMessage(m_nCreateAPResult);
					handler.sendMessage(msg);
				}
				try {
					Thread.sleep(5L);
				} catch (Exception localException) {
				}
			}
		}

		public void start() {
			try {
				thread = new Thread(this);
				running = true;
				startTime = System.currentTimeMillis();
				thread.start();
			} finally {
			}
		}

		public void stop() {
			try {
				this.running = false;
				this.thread = null;
				this.startTime = 0L;
			} finally {
			}
		}
	}
	
	//搜索超时处理线程
	class WTSearchProcess implements Runnable {
		public boolean running = false;
		private long startTime = 0L;
		private Thread thread = null;

		WTSearchProcess() {
		}

		public void run() {
			while (true) {
				if (!this.running)
					return;
				if (System.currentTimeMillis() - this.startTime >= 30000L) {
					// Message localMessage = Message.obtain(handler);
					// localMessage.what = 0;
					// localMessage.sendToTarget();
					Message msg = handler.obtainMessage(m_nWTSearchTimeOut);
					handler.sendMessage(msg);
				}
				try {
					Thread.sleep(10L);
				} catch (Exception localException) {
				}
			}
		}

		public void start() {
			try {
				this.thread = new Thread(this);
				this.running = true;
				this.startTime = System.currentTimeMillis();
				this.thread.start();
			} finally {
			}
		}

		public void stop() {
			try {
				this.running = false;
				this.thread = null;
				this.startTime = 0L;
			} finally {
			}
		}
	}
}


3.最后是最重要的wifi管理类:WifiAdmin,这里有一些常用的函数,比如说创建一个wifi的WifiConfiguration,创建热点,以及获取各种wifi状态等函数

/**
 * wifi管理类
 * 
 * @author way
 * 
 */
public class WifiAdmin {
	private static WifiAdmin wiFiAdmin = null;
	private List<WifiConfiguration> mWifiConfiguration;
	private WifiInfo mWifiInfo;
	private List<ScanResult> mWifiList;
	WifiManager.WifiLock mWifiLock;
	public WifiManager mWifiManager;

	public WifiAdmin(Context paramContext) {
		this.mWifiManager = ((WifiManager) paramContext
				.getSystemService("wifi"));
		this.mWifiInfo = this.mWifiManager.getConnectionInfo();
	}

	public static WifiAdmin getInstance(Context paramContext) {
		if (wiFiAdmin == null)
			wiFiAdmin = new WifiAdmin(paramContext);
		return wiFiAdmin;
	}

	private WifiConfiguration isExsits(String paramString) {
		Iterator localIterator = this.mWifiManager.getConfiguredNetworks()
				.iterator();
		WifiConfiguration localWifiConfiguration;
		do {
			if (!localIterator.hasNext())
				return null;
			localWifiConfiguration = (WifiConfiguration) localIterator.next();
		} while (!localWifiConfiguration.SSID.equals("\"" + paramString + "\""));
		return localWifiConfiguration;
	}

	public void AcquireWifiLock() {
		this.mWifiLock.acquire();
	}

	public void CreatWifiLock() {
		this.mWifiLock = this.mWifiManager.createWifiLock("Test");
	}

	public void OpenWifi() {
		if (!this.mWifiManager.isWifiEnabled())
			this.mWifiManager.setWifiEnabled(true);
	}

	public void ReleaseWifiLock() {
		if (this.mWifiLock.isHeld())
			this.mWifiLock.acquire();
	}

	public void addNetwork(WifiConfiguration paramWifiConfiguration) {
		int i = this.mWifiManager.addNetwork(paramWifiConfiguration);
		this.mWifiManager.enableNetwork(i, true);
	}

	public void closeWifi() {
		this.mWifiManager.setWifiEnabled(false);
	}
	
	public void connectConfiguration(int paramInt) {
		if (paramInt > this.mWifiConfiguration.size())
			return;
		this.mWifiManager
				.enableNetwork(((WifiConfiguration) this.mWifiConfiguration
						.get(paramInt)).networkId, true);
	}
	/**
	 * 根据wifi信息创建一个热点
	 * @param paramWifiConfiguration
	 * @param paramBoolean
	 */
	public void createWiFiAP(WifiConfiguration paramWifiConfiguration,
			boolean paramBoolean) {
		try {
			Class localClass = this.mWifiManager.getClass();
			Class[] arrayOfClass = new Class[2];
			arrayOfClass[0] = WifiConfiguration.class;
			arrayOfClass[1] = Boolean.TYPE;
			Method localMethod = localClass.getMethod("setWifiApEnabled",
					arrayOfClass);
			WifiManager localWifiManager = this.mWifiManager;
			Object[] arrayOfObject = new Object[2];
			arrayOfObject[0] = paramWifiConfiguration;
			arrayOfObject[1] = Boolean.valueOf(paramBoolean);
			localMethod.invoke(localWifiManager, arrayOfObject);
			return;
		} catch (Exception localException) {
		}
	}
	
	/**
	 * 创建一个wifi信息
	 * @param ssid 名称
	 * @param paramString2 密码
	 * @param paramInt 有3个参数,1是无密码,2是简单密码,3是wap加密
	 * @param paramString3 是"ap"还是"wt"
	 * @return
	 */
	public WifiConfiguration createWifiInfo(String ssid, String paramString2,
			int paramInt, String paramString3) {
		WifiConfiguration localWifiConfiguration1 = new WifiConfiguration();
		localWifiConfiguration1.allowedAuthAlgorithms.clear();
		localWifiConfiguration1.allowedGroupCiphers.clear();
		localWifiConfiguration1.allowedKeyManagement.clear();
		localWifiConfiguration1.allowedPairwiseCiphers.clear();
		localWifiConfiguration1.allowedProtocols.clear();
		if (paramString3.equals("wt")) {
			localWifiConfiguration1.SSID = ("\"" + ssid + "\"");
			WifiConfiguration localWifiConfiguration2 = isExsits(ssid);
			if (localWifiConfiguration2 != null)
				mWifiManager.removeNetwork(localWifiConfiguration2.networkId);
			if (paramInt == 1) {
				localWifiConfiguration1.wepKeys[0] = "";
				localWifiConfiguration1.allowedKeyManagement.set(0);
				localWifiConfiguration1.wepTxKeyIndex = 0;
			} else if (paramInt == 2) {
				localWifiConfiguration1.hiddenSSID = true;
				localWifiConfiguration1.wepKeys[0] = ("\"" + paramString2 + "\"");
			} else {
				localWifiConfiguration1.preSharedKey = ("\"" + paramString2 + "\"");
				localWifiConfiguration1.hiddenSSID = true;
				localWifiConfiguration1.allowedAuthAlgorithms.set(0);
				localWifiConfiguration1.allowedGroupCiphers.set(2);
				localWifiConfiguration1.allowedKeyManagement.set(1);
				localWifiConfiguration1.allowedPairwiseCiphers.set(1);
				localWifiConfiguration1.allowedGroupCiphers.set(3);
				localWifiConfiguration1.allowedPairwiseCiphers.set(2);
			}
		} else {
			localWifiConfiguration1.SSID = ssid;
			localWifiConfiguration1.allowedAuthAlgorithms.set(1);
			localWifiConfiguration1.allowedGroupCiphers
					.set(WifiConfiguration.GroupCipher.CCMP);
			localWifiConfiguration1.allowedGroupCiphers
					.set(WifiConfiguration.GroupCipher.TKIP);
			localWifiConfiguration1.allowedGroupCiphers
					.set(WifiConfiguration.GroupCipher.WEP40);
			localWifiConfiguration1.allowedGroupCiphers
					.set(WifiConfiguration.GroupCipher.WEP104);
			localWifiConfiguration1.allowedKeyManagement.set(0);
			localWifiConfiguration1.wepTxKeyIndex = 0;
			if (paramInt == 1) {
				localWifiConfiguration1.wepKeys[0] = "";
				localWifiConfiguration1.allowedKeyManagement.set(0);
				localWifiConfiguration1.wepTxKeyIndex = 0;
			} else if (paramInt == 2) {
				localWifiConfiguration1.hiddenSSID = true;
				localWifiConfiguration1.wepKeys[0] = paramString2;
			} else if (paramInt == 3) {
				localWifiConfiguration1.preSharedKey = paramString2;
				localWifiConfiguration1.allowedAuthAlgorithms.set(0);
				localWifiConfiguration1.allowedProtocols.set(1);
				localWifiConfiguration1.allowedProtocols.set(0);
				localWifiConfiguration1.allowedKeyManagement.set(1);
				localWifiConfiguration1.allowedPairwiseCiphers.set(2);
				localWifiConfiguration1.allowedPairwiseCiphers.set(1);
			}
		}
		return localWifiConfiguration1;
	}	
	
	/**
	 * 端口指定id的wifi
	 * @param paramInt
	 */
	public void disconnectWifi(int paramInt) {
		this.mWifiManager.disableNetwork(paramInt);
	}
	/**
	 * 获取热点名
	 * @return
	 */
	public String getApSSID() {
		try {
			Method localMethod = this.mWifiManager.getClass()
					.getDeclaredMethod("getWifiApConfiguration", new Class[0]);
			if (localMethod == null)
				return null;
			Object localObject1 = localMethod.invoke(this.mWifiManager,
					new Object[0]);
			if (localObject1 == null)
				return null;
			WifiConfiguration localWifiConfiguration = (WifiConfiguration) localObject1;
			if (localWifiConfiguration.SSID != null)
				return localWifiConfiguration.SSID;
			Field localField1 = WifiConfiguration.class
					.getDeclaredField("mWifiApProfile");
			if (localField1 == null)
				return null;
			localField1.setAccessible(true);
			Object localObject2 = localField1.get(localWifiConfiguration);
			localField1.setAccessible(false);
			if (localObject2 == null)
				return null;
			Field localField2 = localObject2.getClass()
					.getDeclaredField("SSID");
			localField2.setAccessible(true);
			Object localObject3 = localField2.get(localObject2);
			if (localObject3 == null)
				return null;
			localField2.setAccessible(false);
			String str = (String) localObject3;
			return str;
		} catch (Exception localException) {
		}
		return null;
	}
	/**
	 * 获取wifi名
	 * @return
	 */
	public String getBSSID() {
		if (this.mWifiInfo == null)
			return "NULL";
		return this.mWifiInfo.getBSSID();
	}

	public List<WifiConfiguration> getConfiguration() {
		return this.mWifiConfiguration;
	}
	/**
	 * 获取ip地址
	 * @return
	 */
	public int getIPAddress() {
		if (this.mWifiInfo == null)
			return 0;
		return this.mWifiInfo.getIpAddress();
	}
	/**
	 * 获取物理地址
	 * @return
	 */
	public String getMacAddress() {
		if (this.mWifiInfo == null)
			return "NULL";
		return this.mWifiInfo.getMacAddress();
	}	
	
	/**
	 * 获取网络id
	 * @return
	 */
	public int getNetworkId() {
		if (this.mWifiInfo == null)
			return 0;
		return this.mWifiInfo.getNetworkId();
	}
	/**
	 * 获取热点创建状态
	 * @return
	 */
	public int getWifiApState() {
		try {
			int i = ((Integer) this.mWifiManager.getClass()
					.getMethod("getWifiApState", new Class[0])
					.invoke(this.mWifiManager, new Object[0])).intValue();
			return i;
		} catch (Exception localException) {
		}
		return 4;
	}
	/**
	 * 获取wifi连接信息
	 * @return
	 */
	public WifiInfo getWifiInfo() {
		return this.mWifiManager.getConnectionInfo();
	}

	public List<ScanResult> getWifiList() {
		return this.mWifiList;
	}

	public StringBuilder lookUpScan() {
		StringBuilder localStringBuilder = new StringBuilder();
		for (int i = 0;; i++) {
			if (i >= 2)
				return localStringBuilder;
			localStringBuilder.append("Index_" + new Integer(i + 1).toString()
					+ ":");
			localStringBuilder.append(((ScanResult) this.mWifiList.get(i))
					.toString());
			localStringBuilder.append("/n");
		}
	}
	
	/**
	 * 设置wifi搜索结果
	 */
	public void setWifiList() {
		this.mWifiList = this.mWifiManager.getScanResults();
	}
	/**
	 * 开始搜索wifi
	 */
	public void startScan() {
		this.mWifiManager.startScan();
	}
}

还有一些自定义View我就不贴出来了,大家下载源码自己看吧。



你可能感兴趣的:([置顶] Android之高仿飞鸽传输热点创建与搜索模块)