wifi的狀態有以下幾種
WIFI_STATE_DISABLED = 1, 已經關閉
WIFI_STATE_DISABLING = 0, 正在關閉
WIFI_STATE_ENABLED = 3, 已經開啟
WIFI_STATE_ENABLING = 2, 正在開啟
WIFI_STATE_UNKNOWN = 4 未知狀態
為什麼會有進行中的操作呢?是由於開啟或關閉一個裝置需要時間。
對wifi的操作就是操作WifiManager類,要想操作Wifi我們首先要擷取Wif服務
WifiManager wifi = (WifiManager)WifiActivity.this.getSystemService(Context.WIFI_SERVICE);
完整例子如下
package com.example.wifi;import android.net.wifi.WifiManager;import android.os.Bundle;import android.app.Activity;import android.content.Context;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;/** * Wifi的開啟關閉操作 只要是對WifiManager類操作 * @author Administrator * */public class WifiActivity extends Activity {private Button open = null;private Button close = null;private Button get = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_wifi);open = (Button)findViewById(R.id.open);close = (Button)findViewById(R.id.close);get = (Button)findViewById(R.id.get);//開啟wifiopen.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubWifiManager wifi = (WifiManager)WifiActivity.this.getSystemService(Context.WIFI_SERVICE);wifi.setWifiEnabled(true);System.out.println("wifi state------>" + wifi.getWifiState());Toast.makeText(WifiActivity.this, "開啟wifi state = " + wifi.getWifiState(), Toast.LENGTH_SHORT).show();}});//關閉wificlose.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubWifiManager wifi = (WifiManager)WifiActivity.this.getSystemService(Context.WIFI_SERVICE);wifi.setWifiEnabled(false);System.out.println("wifi state------>" + wifi.getWifiState());Toast.makeText(WifiActivity.this, "關閉wifi state = " + wifi.getWifiState(), Toast.LENGTH_SHORT).show();}});//擷取wifi的狀態get.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubWifiManager wifi = (WifiManager)WifiActivity.this.getSystemService(Context.WIFI_SERVICE);System.out.println("wifi state------>" + wifi.getWifiState());Toast.makeText(WifiActivity.this, "擷取wifi state = " + wifi.getWifiState(), Toast.LENGTH_SHORT).show();}});}}
正在關閉的
範例程式碼
點擊開啟連結