Android 监听网络状态变化
通过网络连接管理者获取管理对象,使用ConnectivityManager中的getActiveNetworkInfo()方法获取网络连接的额外信息,调用isAvailable()和isConnected()方法判断当前网络是否可用,是否连接。
public class NetworkChangedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
/***
* 全局的网络状态变化监听
*/
if (intent.getAction()!=null && intent!=null){
if (intent.getAction() == ConnectivityManager.CONNECTIVITY_ACTION) {
/*判断当前网络时候可用以及网络类型*/
if (!isNetworkAvailable(context)) {
//无网络状态
} else {
//有网络状态
}
}
}
}
public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = null;
if (connectivityManager != null) {
activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
}
return activeNetworkInfo != null && activeNetworkInfo.isAvailable() && activeNetworkInfo.isConnected();
}
}
千万记得需要在Manifest.xml文件中注册
<receiver android:name=".NetworkChangedReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.INTERNET" />