2017-08-16 61 views
1

我有一个问题,我还没有解决,我需要帮助。如何处理异步任务中的连接超时

当互联网速度慢时,应用程序崩溃。我怎么能检查asyntask中的连接超时。

我做了一个应用程序,有时连接到网络服务来获取数据和我做,使用异步任务

我想就连接超时警告对话框时,用户可以选择他们是否想如果重试或取消,他们选择重试,它会尝试重新连接

public class login extends AsyncTask<Void,Void,Void> { 

    InputStream ins; 
    String status, result, s = null, data = "",js; 
    int ss; 
    int responseCode; 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pdlg.setTitle("Checking"); 
     pdlg.setMessage("Please wait"); 
     pdlg.setCancelable(false); 
     pdlg.show(); 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 
     StringBuilder sb = new StringBuilder(); 
     ArrayList al; 
     try { 
      URL url = new URL("http://....login.php"); 
      String param = "username=" + uname + "&password=" + pass; 
      HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
      connection.setRequestMethod("POST"); 
      connection.setConnectTimeout(15000); 
      connection.setReadTimeout(15000); 
      connection.setDoInput(true); 
      connection.setDoOutput(true); 

      OutputStream os = connection.getOutputStream(); 
      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); 
      bw.write(param); 
      bw.flush(); 
      bw.close(); 

      responseCode = connection.getResponseCode(); 
      if (responseCode == HttpURLConnection.HTTP_OK) { 
       BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
       String line = ""; 
       while ((line = br.readLine()) != null) { 
        sb.append(line + "\n"); 
       } 
      } 
      data = sb.toString(); 
      JSONObject json = new JSONObject(data); 

      status=json.getString("Status");//{"Login Status":"Success","Receipt Details":"No data available"} 

      // js=json.getString("Login");//{"Login":"Failed"} 



     } catch (MalformedURLException e) { 
      Log.i("MalformedURLException", e.getMessage()); 
     } catch (IOException e) { 
      Log.i("IOException", e.getMessage()); 
     } catch (JSONException e) { 
      Log.i("JSONException", e.getMessage()); 
     } 

     return null; 
    } 

    protected void onPostExecute(Void result) { 
     super.onPostExecute(result); 

     String status1=status.trim(); 


     if (status1.equals("Success")) { 
    Toast.makeText(getApplicationContext(), "Login Succes !!", Toast.LENGTH_SHORT).show(); 

      Intent i = new Intent(Login.this, Home.class); 
      startActivity(i); 
      finish(); 
      SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); 
      SharedPreferences.Editor editor = sharedPreferences.edit(); 
      editor.putBoolean("first_time", false); 
      editor.putString("userrname", uname); 
      editor.putString("password",pass); 
      editor.apply(); 
      Toast.makeText(getApplicationContext(),"welcome : "+uname,Toast.LENGTH_LONG).show(); 

     } 

else { 
    Toast t=Toast.makeText(Login.this, "Username or Password is Incorrect", Toast.LENGTH_LONG); 
      t.setGravity(Gravity.BOTTOM,0,0); 
         t.show(); 
} 

     pdlg.dismiss(); 


    } 



    } 

回答

1

您可以使用getErrorStream(),

HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
InputStream inp; 

// if some error in connection 
inp = connection.getErrorStream(); 

检查this根据回答更多细节..

doc返回

如有错误流,则返回null没有出现过错误, 连接没有连接或 服务器没有发送有用数据

1

使用这两catch块来处理ConnectionTimeOut和了socketTimeout例外

 catch (SocketTimeoutException bug) { 
      Toast.makeText(getApplicationContext(), "Socket Timeout", Toast.LENGTH_LONG).show(); 
     } 
     catch (ConnectTimeoutException bug) { 
      Toast.makeText(getApplicationContext(), "Connection Timeout", Toast.LENGTH_LONG).show(); 
     } 
+0

如果有帮助,请接受答案。 –

1

对于连接超时在你的catch块和崩溃,因为没有空检查添加SocketTimeoutException,你正在试图削减在onPostExecute

字符串中,你应该做的这个样子,以及使用状态

if(TextUtil.isEmpty(status)) { 
    pdlg.dismiss(); 
    // We are getting empty response 
    return; 
} 
String status1=status.trim(); 
1

前检查你想要做的是以前在一些很棒的网络库中完成的。所以我敦促你使用widley使用的网络库之一。 排球。

或者如果你想了解你可以只检查响应状态(或状态码应该是408.我猜连接超时)如果它会返回“连接超时”,那么你可以调用你的代码到http客户端再次执行您的任务,您也可以添加一个重试计数来尝试2-3次,然后放弃并发送响应onpostexecute方法。

希望这会有所帮助。

1

你能赶上在代码中连接超时异常,然后将状态设置根据您的要求,为您在onPostExecute该状态显示的警告对话框中

try { 
      URL url = new URL("http://....login.php"); 
      String param = "username=" + uname + "&password=" + pass; 
    // Your URL connection code here 
catch (ConnectTimeoutException e) { 
     Log.e(TAG, "Timeout", e); 
     status="timeout" 
    } catch (SocketTimeoutException e) { 
     Log.e(TAG, " Socket timeout", e); 
     status="timeout" 
    } 

onPostExecute

if (status.equals("timeout")) { 
    // Show Alert Dialog. 
}