使用Asynctask检查Internet是否可访问

时间:2015-04-20 11:32:07

标签: java android android-asynctask

我有这个类来检查Internet是否可访问:

public class NetworkAvailability extends AsyncTask<Context, Boolean, Boolean> {

Context mContext;

private static boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) ListViewActivity.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    if (activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting()) {
        Log.i("Netzwerkstatus: ", "Netzwerk-Verbindung verfügbar");
        return true;
    }
    return false;

}

public NetworkAvailability(Context mContext) {
    this.mContext = mContext;
}

public NetworkAvailability() {
}

@Override
protected Boolean doInBackground(Context... params) {
    if (isNetworkAvailable()) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.de").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500);
            try {
                urlc.connect();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //i ist 200 bei Internetverbindung
            int i = urlc.getResponseCode();
            return (i == 200);
        } catch (IOException e) {
            Log.e("IsInternetAccessible: ", "Konnte Internetverbindung nicht prüfen");
        }
    } else {
        Log.d("IsInternetAccessible:", "Internet nicht verfügbar");
    }
    return false;
}

现在我想在解析xml之前检查互联网是否可访问。 这是我想要使用这个类的片段。

if (networkAvailability.execute()) {
            XMLParser parser = new XMLParser();
            String xml = parser.getXMLFromUrl("http://XXXXXX.de/XX.xml");
            Document doc = parser.getDomElement(xml);

            NodeList nl = doc.getElementsByTagName(KEY_SYSTEM);

            for (int i = 0; i < nl.getLength(); i++) {

                // Neue HashMap erstellen
                HashMap<String, String> map = new HashMap<String, String>();
                Element e = (Element) nl.item(i);

                // Jedes Kind-Knoten zur HashMap
                map.put(KEY_UUID, parser.getValue(e, KEY_UUID));
                map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
                map.put(KEY_JOBTITLE, parser.getValue(e, KEY_JOBTITLE));
                map.put(KEY_JOBINFO, parser.getValue(e, KEY_JOBINFO));
                map.put(KEY_IMAGE, parser.getValue(e, KEY_IMAGE));

                //Hashmap zur ArrayList hinzufügen
                menuItems.add(map);
            }
        } else {
            Log.i("doInBackground:", "Keine Internet-Verbindung");
            return null;
        }

如何在if循环中使用NetworkAvailability类的结果作为条件?

1 个答案:

答案 0 :(得分:0)

你可以做的是创建一个单独的类来检查互联网连接,然后创建该类的对象,并调用该函数,这也将清理你的代码。

public class ConnectionDetector {

    private Context _context;

    public ConnectionDetector(Context context){
    this._context = context;
    }

    public boolean isConnectingToInternet(){
       ConnectivityManager connectivity = (ConnectivityManager)  _context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null) 
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null) 
              for (int i = 0; i < info.length; i++) 
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
   }
}

然后在您的活动中为该ConnectionDetector创建对象,如

ConnectionDetector cd=new ConnectionDetector(this);

然后你想要使用该功能的地方只需调用

if(cd.isConnectingToInternet()){

     //internet available
}else{

     //internet not available
}