【Android】Wifi管理与应用

检测是否有WIFI可用

WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);  
if (mWifiManager != null) {   
	List wifiScanResults = mWifiManager.getScanResults();   
      if (wifiScanResults != null && wifiScanResults.size() != 0) {   
                           
      }   
}  

检测是否开启WIFI

WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);   
if (wifiManager.isWifiEnabled()) {   
	wifiManager.setWifiEnabled(false);   
} else {   
	wifiManager.setWifiEnabled(true);   
}  

Menifest.xml文件进行权限登记

 	
	
	

应用范例

Activity

package com.app.myweb;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class WifiTest extends Activity{
	private WifiManager wifiManager ;
	private Button button;
	private TextView textView1,textView2;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wifi);
		button = (Button) findViewById(R.id.button1);
		textView1 = (TextView) findViewById(R.id.textView1);
		textView2 = (TextView) findViewById(R.id.textView2);
		
		wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		
		if (wifiManager.isWifiEnabled()) {//判断Wifi是否开启
			textView1.setText("WIFI开关:已启用");
			button.setText("关闭Wifi");
		} else {
			textView1.setText("WIFI开关:已关闭");
			button.setText("打开Wifi");
		}
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (button.getText().equals("关闭Wifi")) {
					wifiManager.setWifiEnabled(false);
					textView1.setText("WIFI开关:已关闭");
					button.setText("打开Wifi");
				} else if (button.getText().equals("打开Wifi")) {
					wifiManager.setWifiEnabled(true);
					textView1.setText("WIFI开关:已启用");
					button.setText("关闭Wifi");
				}
			}
		});
		
		StringBuilder sBuilder = new StringBuilder();
		if (wifiManager != null) {
			List wifiResults = wifiManager.getScanResults();
			if (wifiResults != null && wifiResults.size() != 0) {
				for (int i = 0; i < wifiResults.size(); i++) {
					ScanResult wifi = wifiResults.get(i);
					System.out.println(wifi.BSSID);
					sBuilder.append("第"+i+"个可用Wifi:\n");
					sBuilder.append("Wifi名称:"+wifi.BSSID + "\n");
				}
			} else {
				Toast.makeText(this, "请检查Wifi是否开启", Toast.LENGTH_LONG).show();
				sBuilder.append("没有可用Wifi,请检查Wifi是否开启!");
			}
		}
		textView2.setText(sBuilder);
	}
}

XML布局文件




    

        

        


你可能感兴趣的:(Android,android,wifi,管理)