MainActivity.java
package com.example.wifi;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button startWifiButton;
Button stopWifiButton;
Button checkWifiButton;
WifiManager wifiManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startWifiButton = (Button) findViewById(R.id.startWifiButton);
stopWifiButton = (Button) findViewById(R.id.stopWifiButton);
checkWifiButton = (Button) findViewById(R.id.checkWifiButton);
startWifiButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
System.out.println("wifi state --->"+wifiManager.getWifiState());
Toast.makeText(MainActivity.this, "当前wifi网卡状态为"+wifiManager.getWifiState(), Toast.LENGTH_SHORT).show();
}
});
stopWifiButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
System.out.println("wifi state --->"+wifiManager.getWifiState());
Toast.makeText(MainActivity.this, "当前wifi网卡状态为"+wifiManager.getWifiState(), Toast.LENGTH_SHORT).show();
}
});
checkWifiButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
System.out.println("wifi state --->"+wifiManager.getWifiState());
Toast.makeText(MainActivity.this, "当前wifi网卡状态为"+wifiManager.getWifiState(), Toast.LENGTH_SHORT).show();
}
});
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.wifi"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.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>
</manifest>