我在我的应用程序中使用广播接收器类,我正在广播接收器类中对WiFi状态进行操作。如果WiFi断开或连接,则执行一些操作。当wifi连接显示正确的消息,但当wifi断开连接时,显示wifi断开连接消息而不是显示else语句。
这是我的广播接收器类的代码。
public class WifiReceiver extends BroadcastReceiver {
private static final String TAG = "NetworkStateReceiver";
@Override
public void onReceive(final Context context, final Intent intent) {
Log.d(TAG, "Network connectivity change");
if (intent.getExtras() != null) {
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
//check if wifi is connected
if (ni != null && ni.isConnectedOrConnecting()) {
Log.i(TAG, "Network " + ni.getTypeName() + " connected");
}
else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
Log.i(TAG, "wifi disconnected");
}
else {
Log.i(TAG, "Network else state");
}
}
在清单
中注册<receiver android:name=".WifiReceiver">
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
答案 0 :(得分:2)
工作示例
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION))
{
WifiManager manager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
NetworkInfo.State state = networkInfo.getState();
if(state == NetworkInfo.State.CONNECTED)
{
Log.d("Tag","Connected");
}
if(state == NetworkInfo.State.DISCONNECTED)
{
if(manager.isWifiEnabled())
{
Log.d("Tag","Disconnected");
}
}
}
}
答案 1 :(得分:1)
创建Wifi对象
if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION))
{
if (wifi.isWifiEnabled()) {
//perform action
}
else {
//perform action
}
然后
{{1}}