注意:要首先注册开启和关闭WiFi的权限,
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.wyl.wifi" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.wyl.wifi.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <!-- 注册WiFi的权限 --> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"></uses-permission> </manifest>
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); } } }
时间: 2024-10-20 05:07:56