Android之對Wifi的操作

來源:互聯網
上載者:User

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();}});}}

正在關閉的


範例程式碼

點擊開啟連結








相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.