2010-06-12 17 views
2

Thread에서 Activity (스레드를 생성 한 데이터)을 다시 전달하고 싶습니다. Android documentation에 설명처럼스레드에서 데이터를 작업으로 전달합니다.

그래서 내가 뭐하는 거지 :

public class MyActivity extends Activity { 

    [ . . . ] 
    // Need handler for callbacks to the UI thread 
    final Handler mHandler = new Handler(); 

    // Create runnable for posting 
    final Runnable mUpdateResults = new Runnable() { 
     public void run() { 
      updateResultsInUi(); 
     } 
    }; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     [ . . . ] 
    } 

    protected void startLongRunningOperation() { 

     // Fire off a thread to do some work that we shouldn't do directly in the UI thread 
     Thread t = new Thread() { 
      public void run() { 
       mResults = doSomethingExpensive(); 
       mHandler.post(mUpdateResults); 
      } 
     }; 
     t.start(); 
    } 

    private void updateResultsInUi() { 

     // Back in the UI thread -- update our UI elements based on the data in mResults 
     [ . . . ] 
    } 
} 

단 한 가지 내가 여기 실종 - 것 또한 어디서 어떻게 내가 ActivityThread 모두에서 액세스 할 수 mResults 정의되어야하고, 필요에 따라 수정할 수 있습니까? MyActivityfinal으로 정의하면 Thread에 더 이상 변경할 수 없습니다. 예를 들어 ...

감사합니다.

답변

2

mResults를 메서드가 아닌 클래스에 정의하면 어느 위치에서든지 변경할 수 있습니다. 예를 들어 :

protected Object mResults = null; 

(it's faster 때문에 보호 사용)

+2

안드로이드 성능 문서는 패키지 범위, 보호되지를 제안합니다. protected는 구현 세부 정보를 패키지 외부의 하위 클래스로 누출시킬 수 있습니다. – adamp

+0

이것은 '휘발성 (volatile)'이어야합니다. – Gray

관련 문제