Android之对Wifi的操作

wifi的状态有以下几种

WIFI_STATE_DISABLED = 1, 已经关闭
WIFI_STATE_DISABLING = 0, 正在关闭
WIFI_STATE_ENABLED = 3, 已经打开
WIFI_STATE_ENABLING = 2, 正在打开
WIFI_STATE_UNKNOWN = 4 未知状态

为什么会有正在进行的操作呢?是由于打开或关闭一个设备需要时间。

对wifi的操作就是操作WifiManager类,要想操作Wifi我们首先要获取Wif服务

WifiManager wifi = (WifiManager)WifiActivity.this.getSystemService(Context.WIFI_SERVICE);

完整例子如下

package com.example.wifi;

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

/**
 * Wifi的打开关闭操作  只要是对WifiManager类操作
 * @author Administrator
 *
 */
public class WifiActivity extends Activity {

	private Button open = null;
	private Button close = null;
	private Button get = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_wifi);
		
		open = (Button)findViewById(R.id.open);
		close = (Button)findViewById(R.id.close);
		get = (Button)findViewById(R.id.get);
		
		//打开wifi
		open.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				WifiManager wifi = (WifiManager)WifiActivity.this.getSystemService(Context.WIFI_SERVICE);
				wifi.setWifiEnabled(true);
				System.out.println("wifi state------>" + wifi.getWifiState());
				Toast.makeText(WifiActivity.this, "打开wifi state = " + wifi.getWifiState(), Toast.LENGTH_SHORT).show();
			}
		});
		//关闭wifi
		close.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				WifiManager wifi = (WifiManager)WifiActivity.this.getSystemService(Context.WIFI_SERVICE);
				wifi.setWifiEnabled(false);
				System.out.println("wifi state------>" + wifi.getWifiState());
				Toast.makeText(WifiActivity.this, "关闭wifi state = " + wifi.getWifiState(), Toast.LENGTH_SHORT).show();
			}
		});
		//获取wifi的状态
		get.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				WifiManager wifi = (WifiManager)WifiActivity.this.getSystemService(Context.WIFI_SERVICE);
				System.out.println("wifi state------>" + wifi.getWifiState());
				Toast.makeText(WifiActivity.this, "获取wifi state = " + wifi.getWifiState(), Toast.LENGTH_SHORT).show();
			}
		});
	}
}

正在关闭的截图

Android之对Wifi的操作_第1张图片

示例代码

点击打开链接








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