我尝试注册一个Wifi BroadcastReceiver以获取WiFi状态,当它改变.但到目前为止,我没有收到广播的运气.
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <receiver android:name=".WifiReceiver" > <intent-filter> <action android:name="android.net.wifi.WifiManager.WIFI_STATE_CHANGED_ACTION" /> <action android:name="android.intent.action.PHONE_STATE" /> </intent-filter> </receiver> //activity declaration here... </application>
你们知道如何在清单中注册BraodcastReceiver?
我不想在活动中注册,因为当WiFi状态发生变化时,我想监控wifi,无论我的应用程序是否正在运行.
这是我的BroadcastReceiver类:
public class WifiReceiver extends BroadcastReceiver { private final String TAG = "WifiReceiver"; @Override public void onReceive(Context context,Intent intent) { int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,WifiManager.WIFI_STATE_UNKNOWN); String wifiStateText = "No State"; switch (wifiState) { case WifiManager.WIFI_STATE_DISABLING: wifiStateText = "WIFI_STATE_DISABLING"; break; case WifiManager.WIFI_STATE_DISABLED: wifiStateText = "WIFI_STATE_DISABLED"; break; case WifiManager.WIFI_STATE_ENABLING: wifiStateText = "WIFI_STATE_ENABLING"; break; case WifiManager.WIFI_STATE_ENABLED: wifiStateText = "WIFI_STATE_ENABLED"; break; case WifiManager.WIFI_STATE_UNKNOWN: wifiStateText = "WIFI_STATE_UNKNOWN"; break; default: break; } MyLog.d(TAG,"onReceive Broadcast > WiFiState: " + wifiStateText); MyLog.d(TAG,"onReceive Broadcast > Time: " + new Date()); } }
我真的希望得到一些帮助.提前致谢.
解决方法
清单中的接收者应该看起来像这样
<receiver android:name=".WifiReceiver" > <intent-filter> <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> </intent-filter> </receiver>
还可能需要以下许可
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />