Android的WiFi开启与关闭

注意:要首先注册开启和关闭WiFi的权限,




    

    
        
            
                

                
            
        
    
    
	
	
	
	

  MainActivity.java

package com.wyl.wifi;

import android.content.Context;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
	Button btn;
	Button btn2;
	Button btn3;
	TextView tv;
	EditText et;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btn = (Button) findViewById(R.id.btn01);// 检查网卡
		btn2 = (Button) findViewById(R.id.btn02);// 开启网卡
		btn3 = (Button) findViewById(R.id.btn03);// 关闭网卡
		et = (EditText)findViewById(R.id.editText2);
		StartWifiListener start = new StartWifiListener();
		CloseWifiListener close = new CloseWifiListener();
		btn2.setOnClickListener(start);
		btn3.setOnClickListener(close);
	}
	
	class StartWifiListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			//最重要的就是先获取到WifiManager
			WifiManager wifiman = (WifiManager)MainActivity.this.getSystemService(Context.WIFI_SERVICE);
			wifiman.setWifiEnabled(true);//开启WiFi
			System.out.println("wifi state --->"+wifiman.getWifiState());
			Toast.makeText(MainActivity.this, ""+wifiman.getWifiState(), Toast.LENGTH_LONG);
		}
		
	}
	class CloseWifiListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			WifiManager wifiman = (WifiManager)MainActivity.this.getSystemService(Context.WIFI_SERVICE);
			wifiman.setWifiEnabled(false);//关闭WiFi
			System.out.println("wifi state --->"+wifiman.getWifiState());
			Toast.makeText(MainActivity.this, ""+wifiman.getWifiState(), Toast.LENGTH_LONG);
		}
		
	}
	
	
}

  

你可能感兴趣的:(Android的WiFi开启与关闭)