Android中监听系统网络连接打开或者关闭的实现代码
package xxx;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetstateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo gprs = manager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifi = manager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (!gprs.isConnected() && !wifi.isConnected()) {
// network closed
} else {
// network opend
}
}
}
代码自定义了一个BroadcastReceiver,是想监听网络设置变化的事件。
<receiver android:name="xxx.NetstateReceiver">
<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.ACCESS_WIFI_STATE" />