接收系统网络服务的广播接收者
public class NetStateReceiver extends BroadcastReceiver { private Handler handler; public NetStateReceiver(Handler handler) { this.handler = handler; } @Override public void onReceive(Context context, Intent arg1) { 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()) { System.out.println("网络已断开"); SysUtils.sendHandlerMsg(handler, SysConstant.MSG_NET_CONN_DISS); } if (gprs.isConnected() || wifi.isConnected()) { System.out.println("网络已连接"); SysUtils.sendHandlerMsg(handler, SysConstant.MSG_NET_CONN_CONN); } } }
对接收到的广播进行处理
public class MyActivity extends Activity { /** 网络连接状态 true:连接;false:断开 */ public boolean netState = false; private NetStateReceiver receiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int device = GpdService.DEVICE_TYPE_SCANNER;// 一维或二维条码扫描头 MyGpdUtils.startGpdService(this, device); // 注册广播接收者 receiver = new NetStateReceiver(handler); IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(receiver, filter); receiver.onReceive(this, null); } Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case SysConstant.MSG_NET_CONN_DISS:// 网络断开 MyGpdUtils.playSound("网络连接已断开"); netState = false; break; case SysConstant.MSG_NET_CONN_CONN:// 网络连接 // MyGpdUtils.playSound("网络已连接"); netState = true; break; } }; }; }
自定义的消息常量
/** 网络连接消息 */ public static final int MSG_NET_CONN_DISS = 222; public static final int MSG_NET_CONN_CONN = 223;