判断是否有网络


private void setThread() {
    mThread=new Thread(){
        @Override
        public void run() {
            super.run();
            if (Ntil.isNetworkAvailable(CS2Activity.this)){
            mResponse=Ntil.sendData("http://192.168.1.118:8080/classserver/readPartInfo");
                Log.i("调试",mResponse);
            parseData();
             mHandler.sendEmptyMessage(UP_DATA);
            }else {
                mHandler.sendEmptyMessage(NET);
            }
        }
    };
}



package com.example.rachel.ytceshi;import android.content.Context;import android.net.ConnectivityManager;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;/** * Created by Rachel on 2017/3/6. */public class Ntil { private static HttpURLConnection con; private static BufferedReader buff; public static boolean isNetworkAvailable(Context context) { boolean is=false; ConnectivityManager conManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (null==conManager||null==conManager.getActiveNetworkInfo()){ is=false; }else { is=true; } return is; } public static String sendData(String s) { String mResult=""; try { createConnectiom(s); setParams(); mResult=readData(mResult); return mResult; }catch (Exception e){ e.printStackTrace(); }finally { if (buff!=null){ try { buff.close(); } catch (IOException e) { e.printStackTrace(); } } }return mResult; } private static String readData(String mResult) { try { buff=new BufferedReader(new InputStreamReader(con.getInputStream())); String line; if ((line=buff.readLine())!=null){ if (mResult.equals("")){ mResult+=line; }else { mResult+="\n"+line; } } } catch (IOException e) { e.printStackTrace(); } return mResult; } private static void createConnectiom(String s) { try { URL murl=new URL(s); con = (HttpURLConnection) murl.openConnection(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void setParams() { con.setConnectTimeout(20*1000); con.setReadTimeout(20*1000); con.setDoInput(true); con.setDoOutput(true); }}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值