Android管理WIFI

首先,需要权限

   <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>


WIF的状态在WifiManager中定义了常量,都是public static final int类型的,如下

public static final int WIFI_STATE_DISABLED
Wi-Fi is disabled.
Constant Value: 1 (0x00000001)


public static final int WIFI_STATE_DISABLING
Wi-Fi is currently being disabled. The state will change to WIFI_STATE_DISABLED if it finishes successfully.
Constant Value: 0 (0x00000000)


public static final int WIFI_STATE_ENABLED
Wi-Fi is enabled.
Constant Value: 3 (0x00000003)




public static final int WIFI_STATE_ENABLING
Wi-Fi is currently being enabled. The state will change to WIFI_STATE_ENABLED if it finishes successfully.
Constant Value: 2 (0x00000002)



public static final int WIFI_STATE_UNKNOWN
Wi-Fi is in an unknown state. This state will occur when an error happens while enabling or disabling.
Constant Value: 4 (0x00000004)


定义一个并且初始化WifiManager manager==(WifiManager) Context.getSystemService(Context.WIFI_SERVICE);

启动WIFI manager.setWifiEnabled(true);

关闭WIFI manager.setWifiEnabled(false);

获取WIFI状态 manager.getWifiState();返回前面说的五种状态的一种

下面是全部代码

package com.zhycheng.wifi;

import android.app.Activity;
import android.content.Context;
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.Toast;

public class WIFIDemoActivity extends Activity implements OnClickListener {
	Button start,stop,state;
	WifiManager manager;
	
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        start=(Button) findViewById(R.id.startWIFI);
        stop=(Button) findViewById(R.id.stopWIFI);
        state=(Button) findViewById(R.id.getSTATE);
        start.setOnClickListener(this);
        stop.setOnClickListener(this);
        state.setOnClickListener(this);
    }



	@Override
	public void onClick(View v) {
		manager=(WifiManager) this.getSystemService(Context.WIFI_SERVICE);
		
		switch(v.getId())
		{
		case R.id.startWIFI:
			manager.setWifiEnabled(true);
			System.out.println("当前WIFI状态为"+manager.getWifiState());
			Toast.makeText(this, "当前WIFI状态为"+manager.getWifiState(), Toast.LENGTH_SHORT).show();
			
			break;
		case R.id.stopWIFI:
			manager.setWifiEnabled(false);
			System.out.println("当前WIFI状态为"+manager.getWifiState());
			Toast.makeText(this, "当前WIFI状态为"+manager.getWifiState(), Toast.LENGTH_SHORT).show();
			
			break;
		case R.id.getSTATE:
			
			System.out.println("当前WIFI状态为"+manager.getWifiState());
			Toast.makeText(this, "当前WIFI状态为"+manager.getWifiState(), Toast.LENGTH_SHORT).show();
			break;
		}
		
	}
}


示例工程下载:点击打开链接

你可能感兴趣的:(Android管理WIFI)