在Android中,哪些是在进行HTTP调用之前测试Internet的最佳方法?

时间:2016-01-18 07:24:28

标签: android http testing asynchronous

我正在使用 isConnected() 方法来测试互联网是否有效,但是,当移动数据开启但网络不能正常工作时(在旅行时发生)或Wifi已开启但未连接到互联网,该方法返回true并且我的应用程序崩溃。

我做了一些调查,发现我也需要ping谷歌 所以我尝试使用 internetConnectionAvailable(1000) 。即使互联网工作正常,这种方法有时会返回错误。任何人都可以帮我找到更好的解决方案吗?

 //Check device has Internet connection
    public boolean isConnected()    {
        ConnectivityManager connMgr = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
            return true;
        else    {
            //Custom Toast method
            showToast("Unable to connect to Internet !");
            return false;
        }   
    }

//ping google and test internet connection
private boolean internetConnectionAvailable(int timeOut) {
        InetAddress inetAddress = null;
        try {
            Future<InetAddress> future = Executors.newSingleThreadExecutor().submit(new Callable<InetAddress>() {
                @Override
                public InetAddress call() {
                    try {

                        return InetAddress.getByName("www.google.com");
                    } catch (UnknownHostException e) {
                        return null;
                    }
                }
            });
            inetAddress = future.get(timeOut, TimeUnit.MILLISECONDS);
            future.cancel(true);
        } catch (InterruptedException e) {
        } catch (ExecutionException e) {
        } catch (TimeoutException e) {
        }
        Log.e("Google",String.valueOf(inetAddress));
        return inetAddress!=null && !inetAddress.equals("");
    }

1 个答案:

答案 0 :(得分:0)

检查互联网是否已连接...如果是,则调用androidTask()。

 public boolean haveNetworkConnection() {
        boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    haveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    haveConnectedMobile = true;
        }
        return haveConnectedWifi || haveConnectedMobile;
    }

hasNetworkConnection()的调用方法:

 class androidTask extends AsyncTask<Void, Void, String> {
        String BASE_URL = http://abc.def.com/";

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(context);
            pDialog.setMessage("Loading...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(Void... params) {

            HttpURLConnection con = null;
            InputStream is = null;

            hashMapPost.put("report", "users");

            try {
                con = (HttpURLConnection) (new URL(BASE_URL)).openConnection();
                con.setDoInput(true);
                con.setDoOutput(true);
                con.setRequestMethod("POST");
                con.connect();
                OutputStream os = con.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                writer.write(getPostDataString(hashMapPost));
                writer.flush();
                writer.close();
                os.close();
                buffer = new StringBuffer();
                int responseCode = con.getResponseCode();
                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    is = con.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String line;
                    while ((line = br.readLine()) != null)
                        buffer.append(line).append("\r\n");
                    is.close();
                }
                con.disconnect();
                return buffer.toString();
            } catch (Throwable t) {
                t.printStackTrace();
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (Throwable t) {
                }
                try {
                    if (con != null) {
                        con.disconnect();
                    }
                } catch (Throwable t) {
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

        }
    }

方法包含HTTP请求:

{{1}}