2012-06-25 97 views
4

我正在开发一个android应用程序,在每次活动中,我需要将一些数据传递到服务器上,并在进入下一个活动之前取回响应。如果互联网足够快,应用程序就可以正常工作。但随着速度的降低,应用程序部队将关闭。如何处理缓慢的互联网连接,以便它可能不会导致强制关闭应用程序?????缓慢的互联网连接导致部队关闭

这里是代码

public void onClick(View v) { 
    // TODO Auto-generated method stub 
    UserFunctions userFunction = new UserFunctions(); 
    if(userFunction.isNetworkAvailable(getApplicationContext())) 
    { 
     answer=""; 
     for(int check1=0;check1<counter2;check1++){ 
      int check2=0; 
      answer=answer+option4[check1]+"|"; 
      while(check2<counter1){ 
       if(edTxt[check1][check2].getText().toString().equals("")){ 
        answer=""; 
        break; 
       } 
       else{ 
        answer=answer+edTxt[check1][check2].getText().toString()+"|"; 
       } 
       check2++;  
      } 
      if(answer.equals("")){ 
       break; 
      } 
      else{ 
       answer=answer+"||"; 
      } 
     } 
     if(answer.equals("")){ 
      Toast.makeText(this, "Please fill all fields", 600).show(); 
     } 
     else{ 
     userFunction.form1(surveyId,userId , quesNo, answer); 
     if(total>0){ 
      draw(temp); 
     } 
     else{ 
      ques_no++; 
      ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); 
      params.add(new BasicNameValuePair("quesNo", Integer.toString(ques_no))); 
      params.add(new BasicNameValuePair("surveyId", surveyId)); 
      count = getJsonFromURL22(surveyCond, params);   
      j=Integer.parseInt(result); 
      if(j==22) 
      { 
       Toast.makeText(this, "Survey Completed", 600).show(); 
       Intent home=new Intent(Format16.this, SurveyCompleted.class); 
       UserFunctions userFunctions = new UserFunctions(); 
       userFunctions.full(surveyId); 
       Bundle d=new Bundle(); 
       d.putString("userId", userId); 
       home.putExtras(d); 
       startActivity(home); 
      } 
    public String getJsonFromURL22(String url, List<NameValuePair> params){ 
try{ 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost(url); 
    httppost.setEntity(new UrlEncodedFormEntity(params)); 
    HttpResponse response = httpclient.execute(httppost); 
    HttpEntity entity = response.getEntity(); 
    is = entity.getContent(); 
}catch(Exception e){ 
    Log.e("log_tag", "Error in http connection"+e.toString()); 
} 
//convert response to string 
try{ 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
    sb = new StringBuilder(); 
    sb.append(reader.readLine()); 

    String line="0"; 
    while ((line = reader.readLine()) != null) { 
     sb.append(line); 
    } 
    is.close(); 
    result=sb.toString(); 
}catch(Exception e){ 
    Log.e("log_tag", "Error converting result "+e.toString()); 
} 
return result; 
} 
+0

向我们展示一些代码。还有logcat错误。 – Rajesh

+0

你正在做网络在不同的线程继续吧? –

+0

你应该看看这个链接: http://stackoverflow.com/questions/11150583/if-an-activity-takes-long-time-to-load-it-asks-for-force-close-如何对解决次/ 11150845#11150845 –

回答

1

如果互联网足够快,应用程序可以正常工作。但随着速度降低,应用程序部队关闭。

它清楚地表明你正在UI线程上进行网络操作。如果在主线程上执行异步操作,并且如果超过5秒,那么你的应用程序将显示强制关闭对话框对最终用户来说是非常不愉快的。

实际上,如果您尝试在最新的Android版本(即4.0或更高版本)上运行此类应用程序,它将不会允许您运行应用程序,只要它检测到对主要线。

您必须使用AsyncTaskHandlers执行长时间运行的应用程序。

浏览以下博客了解更多。

http://android-developers.blogspot.in/2010/07/multithreading-for-performance.html

+0

lemme尝试AsyncTask ... :) –

+0

是啊有很多例子,如果你面对任何困难:) –

+0

是啊我使用异步方法,我想问题几乎解决了......谢谢.... :) –

0

使用setConnectionTimeoutsetSoTimeout处理连接超时某些部分。

HttpGet httpGet = new HttpGet(url); 
HttpParams httpParameters = new BasicHttpParams(); 
// Set the timeout in milliseconds until a connection is established. 
// The default value is zero, that means the timeout is not used. 
int timeoutConnection = 3000; 
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 
// Set the default socket timeout (SO_TIMEOUT) 
// in milliseconds which is the timeout for waiting for data. 
int timeoutSocket = 5000; 
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 

,并使用AsyncTaskHandlerHandlerThreadrunOnUiThread任何人正从服务器的数据(执行在后台长时间运行的任务)。

+0

设置超时将无助于OP解决问题。 –

+0

当然,设置超时可能会在互联网连接速度缓慢时有所帮助,但如果我们仅仅使用超时来解决OP的ANR问题,他们会问“如何避免java.net.SocketTimeoutException:Socket is not connected错误?” –

3

由于您没有显示任何代码,我猜测您的Android API级别为10或更低,并且您正在UI线程中执行所有网络连接,导致可怕的App Not Responding(ANR)错误。解决此问题的一种方法是使用AsyncTask并将所有网络代码移到那里。当正确完成后,AsyncTaskdoInBackground()将在一个单独的线程中处理您的所有网络,使UI保持响应。

它通常的工作原理是这样的:

private class NetworkTask extends AsyncTask<String, Void, String> { 

     @Override 
     protected String doInBackground(String... params) { 
      // Do all networking here, this will work away in a background thread. 
      // In your case: 
      // HttpResponse response = httpclient.execute(httppost); 
      // Must happen here 
     }  

     @Override 
     protected void onPostExecute(String result) { 
     // dismiss progress dialog if any (not required, runs in UI thread) 
     } 

     @Override 
     protected void onPreExecute() { 
     // show progress dialog if any, and other initialization (not required, runs in UI thread) 
     } 

     @Override 
     protected void onProgressUpdate(Void... values) { 
// update progress, and other initialization (not required, runs in UI thread) 
     } 
} 

如果启用StrictMode,或目标API版本11及更高版本,Android将抛出一个NetworkOnMainThreadException当您尝试这样做。

+0

我已经使用这种方法...似乎itz为我工作... :) :) –

0

这必须是ANR问题而不是强制关闭问题。

您可以使用StrictMode来帮助查找潜在的长时间运行的操作,例如您可能会意外执行主线程的网络。

否则试着放进度条。