0

我只是想编写一个简单的 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;
            }

        }};

}
4

1 回答 1

2

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

TextView TextWifiStatus = new TextView (this);

问候

陈子腾

于 2012-08-24T02:31:03.313 回答