zoukankan      html  css  js  c++  java
  • 是否有网络

    
    
    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+=" "+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);
    }
    }
     
  • 相关阅读:
    Java后端知识体系
    HashMap底层实现整理
    Java线程池
    Spring Boot+Dubbo 入门
    Go 代码记录(一)
    Servlet 复习
    Spring Cloud(二)Eureka:服务注册与发现
    Spring Cloud (一)概述
    数据结构基础知识
    容器技术-Docker入门
  • 原文地址:https://www.cnblogs.com/huangahuo/p/7133272.html
Copyright © 2011-2022 走看看