Android监听手机网络变化
手机网络状态发生变化会发送广播,利用广播接收者,监听手机网络变化
效果图
注册广播接收者
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="……" >
……
<application
…… >
……
<!-- 监听网络状态的广播接收者 -->
<receiver android:name=".receiver.NetworkBroadcastReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</application>
</manifest>
广播接收者
package ……;
import ……;
/**
* Created by kongqw on 2015/11/23.
*/
public class NetworkBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
//如果无网络连接activeInfo为null
NetworkInfo activeInfo = manager.getActiveNetworkInfo();
if (wifiInfo.isConnected()) {
// wifi 网络
Log.i("Network", "wifi 网络");
} else if (mobileInfo.isConnected()) {
// 手机网络
Log.i("Network", "手机网络");
} else if (null == activeInfo) {
// 没有网络
Log.i("Network", "没有网络");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}