我正在尝试实现一个简单的BroadcastReceiver,以便我的活动知道何时连接/断开了WIFI。
我当前的代码如下:
@Override
protected void onResume() {
super.onResume();
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectionManager = (ConnectivityManager) SicPlayerApp.getInstance().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isWifiConnected = connectionManager.getActiveNetworkInfo() != null &&
connectionManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI &&
connectionManager.getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED;
Log.i("testnetwork", "isConnectedOrConnecting: " + isWifiConnected);
}
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
并在我的AndroidManifest.xml中:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
我永远无法在该日志行上获得 true 。
奇怪的是,如果我这样做:
@Override
public void onReceive(Context context, Intent intent) {
new CountDownTimer(3000, 3000){
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
ConnectivityManager connectionManager = (ConnectivityManager) SicPlayerApp.getInstance().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isWifiConnected = connectionManager.getActiveNetworkInfo() != null &&
connectionManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI &&
connectionManager.getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED;
Log.i("testnetwork", "isConnectedOrConnecting: " + isWifiConnected);
}
}.start();
}
它运作完美!