如何在Android中以编程方式显示wifi状态?

时间:2012-08-24 00:33:06

标签: android android-wifi

我只是想编写一个简单的Android应用程序,以编程方式显示WiFi是启用还是禁用。我无法打印Wifi状态。我很确定我的代码是99%正确,但这并不比0%正确更好。

我的代码如下。

package com.jasonhsu.wifitest;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

    private LinearLayout ShowWifiStatus;
    TextView TextWifiStatus;

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ShowWifiStatus = new LinearLayout (this);
        TextView TextWifiStatus = new TextView (this);
        TextWifiStatus.setText("Sorry, your Wifi status program isn't working.");
        this.registerReceiver(this.WifiStateChangedReceiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
        ShowWifiStatus.addView(TextWifiStatus);
        setContentView(ShowWifiStatus);
    }

    private BroadcastReceiver WifiStateChangedReceiver
    = new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub

            int extraWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE , 
                    WifiManager.WIFI_STATE_UNKNOWN);

            switch(extraWifiState){
            case WifiManager.WIFI_STATE_DISABLED:
                TextWifiStatus.setText("WIFI STATE DISABLED");
                break;
            case WifiManager.WIFI_STATE_DISABLING:
                TextWifiStatus.setText("WIFI STATE DISABLING");
                break;
            case WifiManager.WIFI_STATE_ENABLED:
                TextWifiStatus.setText("WIFI STATE ENABLED");
                break;
            case WifiManager.WIFI_STATE_ENABLING:
                TextWifiStatus.setText("WIFI STATE ENABLING");
                break;
            case WifiManager.WIFI_STATE_UNKNOWN:
                TextWifiStatus.setText("WIFI STATE UNKNOWN");
                break;
            }

        }};

}

1 个答案:

答案 0 :(得分:2)

从以下语句中删除第一个“TextView”,以便将新的TextView对象分配给成员变量TextWifiStatus,而不是具有相同名称的局部变量。

TextView TextWifiStatus = new TextView (this);

此致

陈子腾