9

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

4

10 回答 10

24

只需创建一个broadcast receiverwithCONNECTIVITY_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" />
于 2013-09-05T09:43:15.500 回答
10

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

// Check network connection
private boolean isNetworkConnected(){
    ConnectivityManager connectivityManager 
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();    
}
于 2013-09-05T09:43:31.017 回答
8

kotlin的一个小类,支持监控24(Andoird P)版sdk前后上网状态。只需创建/注入这个类并添加一个观察者。在没有 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)
}
于 2020-05-06T09:08:17.037 回答
5

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 和 aBehaviorSubject将网络状态转换为Observable,但是您可以轻松地将其替换为回调,例如

interface NetworkChangedListener {
  fun onConnected()
  fun onDisconnected()
}
于 2019-11-29T15:14:07.107 回答
2

如果你想检查网络状态..首先创建这个类..

    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(); 
于 2013-09-05T09:52:02.700 回答
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

于 2013-09-05T09:43:07.750 回答
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;
}
于 2013-09-05T09:48:55.017 回答
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();
于 2013-12-20T20:28:07.923 回答
0

注意: getActiveNetworkInfo()在 Android 10 中已弃用。NetworkCallbacks改为用于面向 Android 10(API 级别 29)及更高版本的应用。


CONNECTIVITY_ACTION 此常量在 API 级别 28 中已弃用。应用程序应该使用更通用的requestNetwork(NetworkRequest, PendingIntent), registerNetworkCallback(NetworkRequest, PendingIntent)orregisterDefaultNetworkCallback(ConnectivityManager.NetworkCallback)函数来更快、更详细地更新他们关心的网络变化。

于 2020-05-20T15:04:00.767 回答
-1

对于上面使用 networkUtils.getConnectivityStatusString(context) 返回 false 的答案,只需在AndroidManifest.xml文件中添加这一行

<application
 android:usesCleartextTraffic="true"
 ......
 ......
于 2020-03-30T16:43:31.170 回答