Android WIFI控制(開啟、關閉)
Android WIFI控制(開啟、關閉)
資料來源:http://cooking-java.blogspot.tw/2010/07/android-wifi.html
1. WIFI的控制,主要是透過WifiManager來管理WIFI。
2.WifiManagerExample.java
package tw.nicky.WifiManagerExample;
import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class WifiManagerExample extends Activity {
private WifiManager wiFiManager;
private Button turnOnWifiButn;
private Button turnOffWifiButn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 取得WifiManager
wiFiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
turnOnWifiButn = (Button) findViewById(R.id.turnOnWifiButn);
turnOffWifiButn = (Button) findViewById(R.id.turnOffWifiButn);
// 開啟wifi
turnOnWifiButn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//若wifi狀態為關閉則將它開啟
if (!wiFiManager.isWifiEnabled()) {
wiFiManager.setWifiEnabled(true);
}
}
});
// 關閉wifi
turnOffWifiButn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//若wifi狀態為開啟則將它關閉
if (wiFiManager.isWifiEnabled()) {
wiFiManager.setWifiEnabled(false);
}
}
});
}
}
3. main.xml(Layout)
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
>
<Button
android:text=”開啟Wifi”
android:id=”@+id/turnOnWifiButn”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”>
</Button>
<Button
android:text=”關閉Wifi”
android:id=”@+id/turnOffWifiButn”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”>
</Button>
</LinearLayout>
4. AndroidManifest.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”tw.nicky.WifiManagerExample”
android:versionCode=”1″
android:versionName=”1.0″>
<application android:icon=”@drawable/icon” android:label=”@string/app_name”>
<activity android:name=”.WifiManagerExample”
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>
<uses-permission android:name=”android.permission.CHANGE_WIFI_STATE”></uses-permission>
<uses-permission android:name=”android.permission.WAKE_LOCK”></uses-permission>
<uses-permission android:name=”android.permission.ACCESS_WIFI_STATE”></uses-permission>
</manifest>