Android中如何判断是否联网
首先在AndroidManifest.xml中添加与连接网络相关的权限:
- <uses-permission android:name="android.permission.INTERNET"></uses-permission>
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
判断联网的代码如下:
- ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
- NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
- if(networkInfo == null || !networkInfo.isAvailable())
- {
- //当前有可用网络
- }
- else
- {
- //当前无可用网络
- }