如何在android中监控网络状态

时间:2013-09-05 09:39:04

标签: android networking

嘿,我是android新手,请有人帮助我。 我只是想知道能够监控网络连接的库的名称。

10 个答案:

答案 0 :(得分:22)

只需使用broadcast receiver操作创建CONNECTIVITY_CHANGE即可。每当网络连接发生变化时,您都会获得broadcast

<强> NetworkUtil.java

public class NetworkUtil {

    public static int TYPE_WIFI = 1;
    public static int TYPE_MOBILE = 2;
    public static int TYPE_NOT_CONNECTED = 0;


    public static int getConnectivityStatus(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                return TYPE_WIFI;

            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return TYPE_MOBILE;
        } 
        return TYPE_NOT_CONNECTED;
    }

    public static String getConnectivityStatusString(Context context) {
        int conn = NetworkUtil.getConnectivityStatus(context);
        String status = null;
        if (conn == NetworkUtil.TYPE_WIFI) {
            status = "Wifi enabled";
        } else if (conn == NetworkUtil.TYPE_MOBILE) {
            status = "Mobile data enabled";
        } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
            status = "Not connected to Internet";
        }
        return status;
    }
}

广播接收器处理网络状态的变化

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {

        String status = NetworkUtil.getConnectivityStatusString(context);

        Toast.makeText(context, status, Toast.LENGTH_LONG).show();
    }
}

<强> AndroidMenifest.xml

<application  ...>
     ...
        <receiver
            android:name="net.viralpatel.network.NetworkChangeReceiver"
            android:label="NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
      ...
</application>

<强>更新

访问网络状态所需的权限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

答案 1 :(得分:9)

你的问题不明确!
如果您想要检查网络连接,则可以执行以下操作。

// Check network connection
private boolean isNetworkConnected(){
    ConnectivityManager connectivityManager 
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();    
}

答案 2 :(得分:5)

kotlin的小类,它支持在24(Andoird P)版本的sdk之前和之后监视Internet的状态。只需创建/注入此类并添加观察者即可。在没有LiveData的评论版本中。

class ConnectivityListener(private val context: Context) {

    val isConnected = MutableLiveData<Boolean>()

    //region used on api < 24
    private val intentFilter by lazy {
        IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
    }

    private val networkBroadcastReceiver by lazy {
        object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                val isConn = isConnected()
                isConnected.postValue(isConn)
            }
        }
    }
    //endregion

    private val networkCallback by lazy {
        object : ConnectivityManager.NetworkCallback() {
            override fun onAvailable(network: Network) {
                isConnected.postValue(true)
            }

            override fun onLost(network: Network) {
                isConnected.postValue(false)
            }
        }
    }

    init {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            getConnectivityManager()?.registerDefaultNetworkCallback(networkCallback)
        } else {
            context.registerReceiver(networkBroadcastReceiver, intentFilter)
        }
    }

    fun isConnected(): Boolean {
        val activeNetwork = getConnectivityManager()?.activeNetworkInfo
        val isConnected = activeNetwork?.isConnectedOrConnecting == true
        return isConnected
    }

    fun getConnectivityManager() = getSystemService(context, ConnectivityManager::class.java)
}

答案 3 :(得分:1)

如果要检查网络状态..首先创建此类..

    public class ConnectionDetector {

private Context _context;

public ConnectionDetector(Context context){
    this._context = context;
}

public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null) 
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null) 
              for (int i = 0; i < info.length; i++) 
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
}

}

然后每当你想检查状态..

ConnectionDetector cd = new ConnectionDetector(getApplicationContext()); 
Boolean isInternetPresent = cd.isConnectingToInternet(); 

答案 4 :(得分:0)

ConnectivityManager cm =
    (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork.isConnectedOrConnecting();

应检查您目前是否有连接

http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html

答案 5 :(得分:0)

尝试以下方法获取网络状态。

ConnectivityManager Class

本课程的主要职责是:

  • 监控网络连接(Wi-Fi,GPRS,UMTS等)
  • 网络连接更改时发送广播意图
  • 当与网络连接丢失时,尝试“故障转移”到另一个网络
  • 提供允许应用程序查询可用网络的粗粒度或细粒度状态的API
   public static boolean IsNetConnected() {
    boolean NetConnected = false;
    try {
        ConnectivityManager connectivity = (ConnectivityManager) m_context
                .getSystemService(m_context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            NetConnected = false;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        NetConnected = true;
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        NetConnected = false;
    }
    return NetConnected;
}

答案 6 :(得分:0)

由于在典型的Android应用中,我们需要检查用户是否已连接到互联网,因此请创建一个包含所有这些功能的实用工具类,并传递如下所示的上下文:

package utilities;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class Util {
    public boolean isNetworkConnected(Context c){
        ConnectivityManager connectivityManager 
                = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();    
    }
} 

你可以通过以下方式来打电话:

Util utility = new Util();
Toast.makeText(getApplicationContext(),"State is :"+utility.isNetworkConnected(this), Toast.LENGTH_LONG).show();

答案 7 :(得分:0)

ConnectivityManager.CONNECTION_ACTION在Android P上已过时,因此您必须使用基于API级别的解决方案组合。

首先在您的AndroidManifest.xml中声明以下权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
enum class InternetConnectionStatus {
  CONNECTED,
  DISCONNECTED
}

我在Application类中放置了以下代码,以避免受到配置更改的影响。

private var connectionStatusSubject: BehaviorSubject<InternetConnectionStatus> =
    BehaviorSubject.create()


fun observeNetworkChanges() {
    // getSystemService() is the core-ktx version
    val connectivityManager: ConnectivityManager? = getSystemService()
    if (
        BUILD.VERSION.SDK_INT >= BUILD.VERSION_CODES.P &&
        connectivityManager != null
    ) {
      val callback = NetworkChangeCallback(connectionStatusSubject, connectivityManager)
      connectivityManager.registerDefaultNetworkCallback(callback)
    } else {
      val networkChangeBroadcastReceiver =
        NetworkChangeBroadcastReceiver(connectionStatusSubject)
      val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
      registerReceiver(networkChangeBroadcastReceiver, filter)
    }
  }
// API P+
class NetworkChangeCallback(
  private val subject: BehaviorSubject<InternetConnectionStatus>,
  connectivityManager: ConnectivityManager
) : NetworkCallback() {

  init {
    val network: Network? = connectivityManager.activeNetwork
    if (network == null) {
      subject.onNext(DISCONNECTED)
    } else {
      val capabilities: NetworkCapabilities? = connectivityManager.getNetworkCapabilities(network)
      if (capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true) {
        subject.onNext(CONNECTED)
      } else {
        subject.onNext(DISCONNECTED)
      }
    }
  }

  override fun onAvailable(network: Network) {
    subject.onNext(CONNECTED)
  }

  override fun onLost(network: Network) {
    subject.onNext(DISCONNECTED)
  }
}
// Below API P
class NetworkChangeBroadcastReceiver(
  private val subject: BehaviorSubject<InternetConnectionStatus>
) : BroadcastReceiver() {
  override fun onReceive(
    context: Context,
    intent: Intent
  ) {
    val noConnectivity: Boolean = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)
    if (noConnectivity) {
      subject.onNext(DISCONNECTED)
    } else {
      subject.onNext(CONNECTED)
    }
  }
}

我正在使用RxJava和BehaviorSubject将网络状态转换为Observable,但是您可以轻松地将其替换为类似以下内容的回调

interface NetworkChangedListener {
  fun onConnected()
  fun onDisconnected()
}

答案 8 :(得分:0)

注意::在Android 10中不推荐使用getActiveNetworkInfo()。对于以Android 10(API级别29)及更高版本为目标的应用,请使用NetworkCallbacks


CONNECTIVITY_ACTION 该常数在API级别28中已弃用。应用程序应使用功能更广泛的requestNetwork(NetworkRequest, PendingIntent)registerNetworkCallback(NetworkRequest, PendingIntent)registerDefaultNetworkCallback(ConnectivityManager.NetworkCallback)函数,以更快,更详细地更新他们关心的网络更改。

答案 9 :(得分:-1)

对于以上答案,使用 networkUtils.getConnectivityStatusString(context)返回false只需在 AndroidManifest.xml 文件

中添加此行
<application
 android:usesCleartextTraffic="true"
 ......
 ......