2017-02-22 2 views
-1

외부 클래스를 AsyncTask으로 확장하면 웹 사이트에서 문자열을 가져와 JSONObject 또는 JSONArray으로 구문 분석 할 수 있습니다. 현재 결과를 얻으려면 .get() 메서드를 사용하지만 서버가 응답하기를 기다리는 동안 응용 프로그램은 프레임을 삭제합니다. 많은 다른 클래스의 데이터를 얻고 있기 때문에 재사용이 가능합니다. 내 AsyncTask를 클래스 :UI 스레드를 차단하지 않고 AsyncTask의 결과를 얻는 방법?

public class JsonTask extends AsyncTask<String, String, String> { 
    protected String doInBackground(String...params) { 

     HttpURLConnection connection = null; 
     BufferedReader reader = null; 

     try { 
      Log.d("Response: ", "> Establishing Connection"); 
      URL url = new URL(params[0]); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.connect(); 


      InputStream stream = connection.getInputStream(); 

      reader = new BufferedReader(new InputStreamReader(stream)); 

      StringBuffer buffer = new StringBuffer(); 
      String line = ""; 

      while ((line = reader.readLine()) != null) { 
       buffer.append(line + "\n"); 
       Log.d("Response: ", "> " + line); 

      } 

      return buffer.toString(); 


     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      if (connection != null) { 
       connection.disconnect(); 
      } 
      try { 
       if (reader != null) { 
        reader.close(); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return null; 
    }} 

지금 내가 단순히하여 데이터를 얻고있다 :

String result = new JsonTask().execute(url).get(); 
+0

@RichArt - 아마도 AsyncTask.execute()는 비동기 작업 인스턴스 자체를 반환하기 때문에 'String'또는 다른 종류의 결과는 반환하지 않기 때문일 수 있습니다. –

답변

1

get 메소드에 대한 문서 당으로 :

대기 계산이 완료하기 위해 필요한 경우, 그 결과를 가져온다.

따라서 결과를 반환하는 백그라운드 작업이 완료 될 때까지 UI가 차단됩니다.

onPostExecute이 수신기라고하는 JsonTask에서 doInBackground의 반환 값을 허용하는 수신기를 만들 수 있습니다.

0

다시 document을 읽을 수 있다고 생각합니다.

  1. onPreExecute()
  2. doInBackground (에 Params ...)
  3. onProgressUpdate (진행 ...)
  4. : 비동기 태스크 실행

    는 태스크 4 단계로 간다 onPostExecute (Result), 백그라운드 계산이 끝난 후에 UI 스레드에서 호출됩니다. 백그라운드 계산의 결과는이 단계에 매개 변수로 전달됩니다.

관련 문제