java Android网络状态接收器。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Android网络状态接收器。相关的知识,希望对你有一定的参考价值。
package com.dev.network;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.util.ArrayList;
import java.util.List;
public class NetworkStateReceiver extends BroadcastReceiver {
protected List<NetworkStateReceiverListener> listeners;
protected Boolean connected;
public NetworkStateReceiver() {
listeners = new ArrayList<>();
connected = null;
}
public void onReceive(Context context, Intent intent) {
if (intent == null || intent.getExtras() == null)
return;
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
if (ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
connected = true;
} else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
connected = false;
}
notifyStateToAll();
}
@SuppressWarnings("Convert2streamapi")
private void notifyStateToAll() {
for (NetworkStateReceiverListener listener : listeners)
notifyState(listener);
}
private void notifyState(NetworkStateReceiverListener listener) {
if (connected == null || listener == null)
return;
if (connected)
listener.networkAvailable();
else
listener.networkUnavailable();
}
public void addListener(NetworkStateReceiverListener l) {
listeners.add(l);
notifyState(l);
}
public interface NetworkStateReceiverListener {
void networkAvailable();
void networkUnavailable();
}
}
以上是关于java Android网络状态接收器。的主要内容,如果未能解决你的问题,请参考以下文章
如何在android上获取网络状态变化? [复制]
java Android的网络连接接收器。无论何时连接或断开网络,都会通知您
Android 通过广播获取网络状态
Android 9.0 网络架构
Android 9.0 网络架构
Android5.0网络之ipv6