Android:等待服务器响应一分钟,否则显示警告对话框



我需要显示一个对话框,如果互联网网络低,从服务器端响应的时间超过1分钟。如何完成这项任务。我使用下面的代码。但这不是故意的。:

try
{
HttpConnectionParams.setConnectionTimeout(hc.getParams(),60000);
 int timeoutSocket = 60*1000;
  HttpConnectionParams.setSoTimeout(hc.getParams(), timeoutSocket);
}

 catch(ConnectTimeoutException e){
                                    //System.out.println(e);
                                    m_Progress.cancel();
                                    alertDialog  = new AlertDialog.Builder(AdminEbooks.this).create();
                                    //alertDialog.setTitle("Reset...");
                                   // System.out.println("internet not available");
                                    alertDialog.setMessage("Low internet connectivity?");
                                    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                                       public void onClick(DialogInterface dialog, int which) {
                                           alertDialog.cancel();
                                       }
                                    });
                                }

我是这样做的:

    public void UseHttpConnection(String url, String charset, String query) {
    try {
        System.setProperty("http.keepAlive", "false");
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.setConnectTimeout(15000 /* milliseconds */);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Charset", charset);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded;charset=" + charset);
        OutputStream output = null;
        try {
            output = connection.getOutputStream();
            output.write(query.getBytes(charset));
        } catch (IOException e) {
            e.printStackTrace();
            showError2("Check your network settings!");
        } finally {
            if (output != null)
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        int status = ((HttpURLConnection) connection).getResponseCode();
        Log.d("", "Status : " + status);
        for (Entry<String, List<String>> header : connection
                .getHeaderFields().entrySet()) {
            Log.d("Headers",
                    "Headers : " + header.getKey() + "="
                            + header.getValue());
        }
        InputStream response = new BufferedInputStream(connection.getInputStream());
        int bytesRead = -1;
        byte[] buffer = new byte[30 * 1024];
        while ((bytesRead = response.read(buffer)) > 0) {
            byte[] buffer2 = new byte[bytesRead];
            System.arraycopy(buffer, 0, buffer2, 0, bytesRead);
            handleDataFromSync(buffer2);
        }
        connection.disconnect();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        showError2("Check your network and server settings!");

    } catch (IOException e) {
        showError2("Check your network settings!");
        e.printStackTrace();
    }
}

基本上,如果你的连接超时,它会给你一个IOException,你需要抓住它并在那里创建警报对话框。至少我是这么做的,而且效果很好

创建一个检查响应时间的方法,

public boolean checkURL() {
    boolean exist = false;
    try {
        URL url=new URL("http://.................");
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setConnectTimeout(60000);
        urlConnection.connect();
        exist = true;
    } catch(Exception  e) {
        e.printStackTrace();
         exist = false;
    }
    return exist;
}

如果在60秒内没有响应,它将返回闪光

现在执行条件

if(chcekURL){
} else {
                                    alertDialog  = new AlertDialog.Builder(AdminEbooks.this).create();
                                    //alertDialog.setTitle("Reset...");
                                   // System.out.println("internet not available");
                                    alertDialog.setMessage("Low internet connectivity?");
                                    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                                       public void onClick(DialogInterface dialog, int which) {
                                           alertDialog.cancel();
                                       }
                                    });
}

听起来你需要把它放在后台线程中。我推荐使用AsyncTask。

您至少需要重写onPreExecute()doInBackground()onPostExecute()才能完成您想要做的事情。

onPreExecute()onPostExecute()在UI线程上执行,所以你的对话框可以在这些方法中显示。

我建议doInBackground()返回boolean,以便onPostExecute()可以显示正确的对话框。

对于我的对话框我只使用

String error = e.toString();
            Dialog d = new Dialog(this);
            d.setTitle("Dialog Title");
            TextView tv = new TextView(this);
            tv.setText(error);
            d.setContentView(tv);
            d.show();

最新更新