很简单,所以直接看代码
代码如下:
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,是想监听网络设置变化的事件。
Manifest文件里注册监听。
代码如下:
<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" />