2010-08-16 4 views
1

문제가 있습니다.
1. 두 개의 스레드가 있습니다. 'worker'스레드와 'UI'스레드가 있습니다.
2. 작업자가 서버에서 데이터를 기다리는 동안 계속 UI 스레드에 알립니다.
3. 업데이트 UI에서 화면에 토스트 메시지가 표시됩니다. 이 말한대로Android의 옵저버 패턴

3 단계 문제 :

android.view.ViewRoot $ CalledFromWrongThreadException : 견해를 만질 수있는 뷰 계층 구조를 생성 만 원래 스레드.

runHandler를 사용하면 runOnUIThread가 서버에서 데이터를 지속적으로 확인해야하므로 UI ​​스레드 (UI에서 webview가 표시됨)의 속도가 느려집니다.

답변

2

이것을 구현하려면 AsyncTask를 사용하십시오. doInBackground를 오버라이드하여 데이터를 가져온 다음 (별도의 스레드에서 실행) onPostExecute()를 재정 의하여 토스트를 표시합니다 (UI 스레드에서 실행 됨).

여기 http://www.screaming-penguin.com/node/7746

그리고 여기가 official docs 좋은 예에게 있습니다.

UPD : 부분 진행 상황을 처리하는 방법에 대한 예제.

class ExampleTask extends AsyncTask<String, String, String>{ 

    @Override 
    protected String doInBackground(String... params) { 
     while(true){ 
      //Some logic on data recieve.. 
      this.publishProgress("Some progress"); 
      //seee if need to stop the thread. 
      boolean stop = true; 
      if(stop){ 
       break; 
      } 
     } 
     return "Result"; 
    } 

    @Override 
    protected void onProgressUpdate(String... values) { 
     super.onProgressUpdate(values); 
     //UI tasks on particular progress... 
    } 
} 
+0

감사합니다. 실제로 데이터가 서버로부터 약간의 간격으로오고 다시 UI를 업데이트해야합니다. 이 예제에서는 doInbackground가 버튼을 클릭 할 때만 실행되지만 내 경우에는 누군가 (스레드)가 항상 서버에서 데이터를 받고 자체 업데이트 UI에 전달할 준비가되어 있어야합니다. 그 사이에 UI sud는 정상적으로 작동합니다 (webview) .... – Placidnick

+0

다른 부분의 데이터를 얻을 때마다 publishProgress를 호출 할 수 있습니다. 업데이트 된 답변을 참조하십시오. –

+0

ohhh 와우 ...... 나는 당신의 큰 시간 팬이다 :) Konstantin rocks !!! 감사합니다. – Placidnick

2

서비스를 사용하고 활동을 서비스에 바인딩합니다. 그런 다음 새로운 데이터가있을 때 서비스에서 브로드 캐스트를 보낼 수 있습니다.

+0

샘플 코드 나 참고 자료를 제안 해주세요. 제게 도움이 될 수 있습니다. 채팅을 구현해야하므로 1.사용자가 다른 활동을하고 채팅 활동으로 돌아 오면 업데이트 된 채팅을 받아야합니다. – Placidnick

1

안드로이드의 객체 관찰 패턴?

정의 : 옵저버 패턴은 하나의 객체가 상태를 변경하는 경우, 그 부양 가족의 모든 통지하고 자동으로 업데이트되도록 객체 사이에 일대 다 의존성을 정의합니다.

 The objects which are watching the state changes are called observer. Alternatively observer are also called listener. The object which is being watched is called subject. 

Example: View A is the subject. View A displays the temperature of a  container. View B display a green light is the temperature is above 20 degree Celsius. Therefore View B registers itself as a Listener to View A. If the temperature of View A is changed an event is triggered. That is event is send to all registered listeners in this example View B. View B receives the changed data and can adjust his display. 

Evaluation: The subject can registered an unlimited number of observers. If a new listener should register at the subject no code change in the subject is necessary.