public interface GetConnectState { public void GetState(boolean isConnected); }
@Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); //注册广播 this.mReceiver = new ConnectReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(mReceiver, intentFilter); } /** * 广播,将服务接收到的数据传到界面 * @author WJD * */ public class ConnectReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub if (intent.getAction().equals( ConnectivityManager.CONNECTIVITY_ACTION)) { Timer timer = new Timer(); timer.schedule(new QunXTask(), new Date()); } } } /** * 定时器线程 * * @author WJD * */ class QunXTask extends TimerTask { @Override public void run() { // TODO Auto-generated method stub if (isNetConnect()) { isConnected = true; } else { isConnected = false; } //设置连接状态 if (onGetConnectState != null) { onGetConnectState.GetState(isConnected); } } }
/** * 判断是否有网络 * @return */ private boolean isNetConnect() { //初始化网络管理器 ConnectivityManager conMag = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); if (conMag == null) { return false; } else { //获取所有的网络连接,包括wifi,和移动网 NetworkInfo[] infos = conMag.getAllNetworkInfo(); if (infos != null) { for (int i = 0; i < infos.length; i++) { //判断是否处于连接状态 if (infos[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; }
Intent intent = new Intent(); intent.setClass(this, NetWrorkServer.class); bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);其次要定义一个监听器
/** * 网络状态监听事件 */ private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub } @Override public void onServiceConnected(ComponentName name, IBinder service) { // TODO Auto-generated method stub mNetWrorkServer = ((NetWrorkServer.MyBinder) service).getServer(); mNetWrorkServer.setOnGetConnectState(new GetConnectState() { @Override public void GetState(boolean isConnected) { // TODO Auto-generated method stub if (isConnected) { mHandler.sendEmptyMessage(1); } else { mHandler.sendEmptyMessage(0); } } }); } };然后就是显示,当然是用到Handler来更新UI
class MyHandler extends Handler { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); switch (msg.what) { case 0: text_mob.setText("网络连接失败"); break; case 1: text_mob.setText("网络连接成功"); break; default: break; } } }5.最后不要忘了把监听器关闭
@Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if (mNetWrorkServer != null) { unbindService(serviceConnection); } }
希望有大牛指导,提供更强劲的思路!!!
转载自:http://www.cnblogs.com/wjdawx/p/3624865.html