2012-03-31 5 views
2

나는 mysql 서버에서 Google지도 용 좌표 쌍을 다운로드해야하는 애플리케이션을 사용하고 있습니다. 이 작업은 PHP와 일반 httpost를 사용하여 성공적으로 수행 할 수 있지만 앱을 종료하면 몇 초 동안 앱이 정지됩니다.비동기 HTTP 게시물 android

서버가 처리를 끝내고 결과를 보낼 때까지 동결을 방지하기 위해 httppost를 비동기로 만들어야한다고 읽었습니다.

요점은 정상적인 httpost와 같은 json 배열에서 그 결과가 필요하다는 것입니다.

예를 들어,이 httppost가있는 경우.

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); 

try { 
    // Add your data 
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
    nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

    // Execute HTTP Post Request 
    HttpResponse response = httpclient.execute(httppost); 
} catch (ClientProtocolException e) { 
    // TODO Auto-generated catch block 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
} 

String result11 = null; 
// convert response to string 
try { 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is11, "iso-8859-1"), 8); 
    StringBuilder sb = new StringBuilder(); 
    sb.append(reader.readLine() + "\n"); 
    String line = "0"; 
    while ((line = reader.readLine()) != null) { 
     sb.append(line + "\n"); 
    } 
    is11.close(); 
    result11 = sb.toString(); 
} catch (Exception e) { 
    Log.e("log_tag", "Error converting result " + e.toString()); 
} 

// parsing data 
try { 
    JSONArray jArray1 = new JSONArray(result11); 
} catch (JSONException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

어떻게 내가 비동기 게시물로 변환하여 동결을 피할 수 있습니까?

+0

난 당신의 코드도 그대로 컴파일하지만, ['EntityUtils.toString (response.getEntity())'(http://stackoverflow.com/a 이용하시기 바랍니다 수있는 방법을 몰라/2324739/180740)를 사용하는 것이 좋습니다. 전자는 코드가 적고 오류 처리가 올바르며 서버에서 보낸 문자 인코딩을 준수합니다. –

답변

1

당신은 버튼 클릭에이 작업을 수행 할 가정 :

public void onClick(View v) { 
    new Thread(new Runnable() { 
     public void run() { 
      //your code here 
     } 
    }).start(); 
} 

을 기본적으로 UI가 동결되지 않도록 별도의 스레드 (다른 UI 스레드)에서 IO를 많이 사용하는 작업을 가하고 있습니다.

+0

잠시 동안 노력하고 있습니다. 답장을 보내 주셔서 감사합니다 :) – user878813

2

새로운 스레드를 시작하기보다는 본격적인 AsyncTask를 사용하는 것이 좋습니다. 그것은 훨씬 더 많은 것을 통제합니다.

private class DoPostRequestAsync extends AsyncTask<URL, Void, String> { 
    protected String doInBackground(URL url) { 
     //Your download code here; work with the url parameter and then return the result 
     //which if I remember correctly from your code, is a string. 
     //This gets called and runs ON ANOTHER thread 
    } 

    protected void onPostExecute(String result) { 
     //This gets called on the interface (main) thread! 
     showDialog("Done! " + result); 
    } 
} 

원하는 활동 클래스 내에 새 클래스 구현을 배치하십시오. AsyncTask를에 대한 추가 정보를 원하시면이 링크를 클릭하십시오 :

http://developer.android.com/reference/android/os/AsyncTask.html

5

쉽게 비동기 작업을 실행하는 데 사용할 수있는 좋은 클래스 AsyncTask 있습니다. 당신은 서브 클래스에 코드를 삽입 할 경우이 끝낼 수 있습니다

new FetchTask().execute(); 

추가 자료 :

  • Painless Threading - developer.android.com
  • public class FetchTask extends AsyncTask<Void, Void, JSONArray> { 
        @Override 
        protected JSONArray doInBackground(Void... params) { 
         try { 
          HttpClient httpclient = new DefaultHttpClient(); 
          HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); 
    
          // Add your data 
          List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
          nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
          nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); 
          httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    
          // Execute HTTP Post Request 
          HttpResponse response = httpclient.execute(httppost); 
    
          BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "iso-8859-1"), 8); 
          StringBuilder sb = new StringBuilder(); 
          sb.append(reader.readLine() + "\n"); 
          String line = "0"; 
          while ((line = reader.readLine()) != null) { 
           sb.append(line + "\n"); 
          } 
          reader.close(); 
          String result11 = sb.toString(); 
    
          // parsing data 
          return new JSONArray(result11); 
         } catch (Exception e) { 
          e.printStackTrace(); 
          return null; 
         } 
        } 
    
        @Override 
        protected void onPostExecute(JSONArray result) { 
         if (result != null) { 
          // do something 
         } else { 
          // error occured 
         } 
        } 
    } 
    

    다음을 사용하여 작업을 시작할 수 있습니다

  • AsyncTask - developer.android.com
3

android-async-http (http://loopj.com/android-async-http/) 라이브러리를 사용하는 것이 좋습니다. 그것은 안드로이드 비동기 http를 간단하고 우아한 호출합니다.

+1

불행히도 초보자가 모든 것을 함께 쓰는 방법을 이해하기 쉽도록 데모를 제공하는 데는 몇 가지 데모가 있습니다.이 경우에는 URL에 데이터를 게시하고 JSON을 사용하여 응답을 처리하는 것과 같습니다. 나는 그것이 모두 거기에 있고 매우 강력하고 똑똑하다고 생각하지만 몇 가지 예들이 분명 도움이 될 것입니다. – richey

+1

나는 그것을 사용했고 쉽게 시작한다는 것을 알았다. 필자는 http://loopj.com/android-async-http/의 "권장 용도"섹션에서 제공된 코드 샘플로 시작했습니다. 쿠키를 계속 유지하고 SSL (신뢰할 수 있고 신뢰할 수 없음)과 작동하도록하는 등 특정 일을 배우고 수행하며 장치가 온라인인지 아닌지 확인하는 등의 추가 작업을 수행합니다. 이러한 모든 문제는 이 라이브러리 또는 Android API를 사용하는지 여부를 처리해야합니다. – krishnakumarp

1

ion과 같은 비동기 http 라이브러리를 사용하십시오. https://github.com/koush/ion

모든 스레딩 및 비동기 상용구가 처리됩니다.

이것은 Ion을 사용하는 비동기식 코드입니다. 훨씬 더 간단 :

Ion.with(context) 
.load("http://www.yoursite.com/script.php") 
.setBodyParameter("id", "12345") 
.setBodyParameter("stringdata", "AndDev is Cool!") 
.asJsonArray() 
.setCallback(new FutureCallback<JsonArray> { 
    void onCompleted(Exception e, JsonArray result) { 
    // do something with the result/exception 
    } 
}); 
관련 문제