2013-11-15 4 views
0

나는 이것에 대해 꽤 많은 논의가 있음을 알고 있지만, 내가 발견 한 것들 중 어느 것도 나의 혼란을 해소 할 수는 없다.
Android SDK를 처음 사용하고 Java 기술이 평균적입니다.안드로이드 새로 고침 스레드로부터의 TextView

다음과 같은 문제가 있습니다.
내 MainActivity - OnCreate() fct에서. 스레드 (Receiver)를 시작하여 SocketStream에서 데이터를 수신합니다. 이 쓰레드는 새로운 데이터가 스트림에서 읽혀질 때 GUI의 TextView-Element를 새로 고쳐야한다.
간단하지만 적절한 방법은 무엇입니까? ASyncTask에 대해 읽었지만 구현 방법을 이해하지 못했습니다.

public class MainActivity extends Activity 
{ 
    ExecutorService myExecutor; 

    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     System.out.println("this is a test"); System.out.flush(); 

     try 
     { 
      myExecutor = Executors.newCachedThreadPool(); 
      myExecutor.execute(Receiver.getInstance()); 
     } 
     catch (IOException e) 
     { 
      e.printStackTrace(); 
     } 
    } 

...

public class Receiver implements Runnable 
{ 
[...] 
    public void run() 
    { 
     while (true) 
     { 
      //blocking system-io-call to read data from socket.. 
      //extract information 
      // *** update textView *** ?? 
     } 
    } 
} 

답변

2

당신은 (귀하의 경우 MainActivity에서) GUI를 변경하는 GUI 스레드에서 핸들러를 구현할 수 있습니다

public Handler handler = new Handler() { 
     @Override 
     public void handleMessage(Message msg) { 
      //refresh textview 
     } 
    }; 

및보다 것은 다른 스레드

에서 호출
activity.handler.sendEmptyMessage(what); 

수신기에 대한 자신의 생성자를 r에 :

public class Receiver implements Runnable 
{ 
[...] 
    MainActivity activity; 
    public Receiver(MainActivity activity){ 
     this.activity = activity; 
    } 


    public void run() 
    { 
     while (true) 
     { 
      //blocking system-io-call to read data from socket.. 
      //extract information 
      // *** update textView *** ?? 
      activity.handler.sendEmptyMessage(0); 
     } 
    } 
} 
+0

합니다. 원격 처리기가 있는지 어떻게 알 수 있습니까? – user2950911

+0

@ user2950911 당신은 수신기에 대한 자신의 생성자를 작성할 수 있습니다. 공용 수신자 (MainActivity 활동) {this.activity = activity;}를 작성하고 수신자 인스턴스를 작성할 때 활동을 설정하십시오. – Suvitruf

2

당신이이 예입니다 runOnUiThread

public class Receiver implements Runnable 
{ 
[...] 
    public void run() 
    { 
     while (true) 
     { 
      //blocking system-io-call to read data from socket.. 
      //extract information 

     runOnUiThread(new Runnable() { 
       public void run() { 
        // *** update textView *** ?? 
       } 
      }); 
    } 
} 
} 
1

사용할 수 있습니다

카운터 클래스 생성 :

public class Counter implements Runnable 
{ 
    private ICounterEvents listener; 
    public static Thread OBJ_THREAD = null; 

    public Counter() 
    {  
     OBJ_THREAD = new Thread(this);   
    } 

    public void setCountListener(ICounterEvents listener) 
    { 
     this.listener = listener; 
    } 

    public void start() 
    {  
     OBJ_THREAD.start(); 
    }      

    @Override 
    public void run() 
    { 
     for(int i = 0; i < 100; i++) 
     { 
      try 
      { 
       Thread.sleep(1000); 
      } 
      catch (InterruptedException e) 
      {    
       e.printStackTrace(); 
      } 

      Message msg = Message.obtain(); 
      msg.obj = i;    
      this.handler.sendMessage(msg); 
     } 
    } 

    private Handler handler = 
      new Handler() 
      { 
       @Override 
       public void handleMessage(Message msg) 
       { 
        if(Counter.this.listener != null) 
        { 
         int value = (Integer)msg.obj; 
         Counter.this.listener.countChanged(value); 
        } 
       } 
      }; 
} 

을하고, 인터페이스 클래스를 생성 :

(210)와 메인 레이아웃보다 텍스트 뷰와 버튼, 을 만들고 MainActivity에서에서 onCreate 메서드에서이 코드를 사용, 컴파일러는 어떤 '활동'을 모르는 내 수신기 클래스에서

public class MainActivity extends Activity implements ICounterEvents, OnClickListener 
{ 
    private TextView txtCounter; 
    private Button btnStart; 
    private Counter counter; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     this.setupViews(); 
    } 

    private void setupViews() 
    { 
     this.counter = new Counter(); 
     this.counter.setCountListener(this); 

     this.txtCounter = (TextView)findViewById(R.id.txtCount); 
     this.btnStart = (Button)findViewById(R.id.btnStart);  

     this.btnStart.setOnClickListener(this); 
    } 

    @Override 
    public void onClick(View v) 
    {  
     this.counter.start(); 
    } 

    public void countChanged(int value) 
    { 
     try 
     { 
      this.txtCounter.setText(value + ""); 
     } 
     catch (Exception e) 
     {   

     } 
    } 
} 
관련 문제