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