Android中判断网络是否连接实例详解
在android中,如何监测网络的状态呢,这个有的时候也是十分重要的,方法如下:
代码如下 | 复制代码 |
publicclassConnectionDetector {
privateContext _context;
publicConnectionDetector(Context context){ this._context = context; }
publicbooleanisConnectingToInternet(){ ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); if(connectivity !=null) { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if(info !=null) for(inti =0; i < info.length; i++) if(info[i].getState() == NetworkInfo.State.CONNECTED) { returntrue; }
} returnfalse; } |
调用:
代码如下 | 复制代码 |
ConnectionDetector cd =newConnectionDetector(getApplicationContext());
Boolean isInternetPresent = cd.isConnectingToInternet();// |