2011-06-03 77 views

回答

5

如果你不想使用的AsyncTask,嘗試在您的主要活動有一個內部類(ResponseHandler所)觀察者模式,對不起,我不可能得到格式正確的但是我相信你的想法

public class WorkerThread extends Observable implements Runnable { 
public void run() { 
    try { 
      DoSomething(); 
      String response = "Doing something"; 
      setChanged(); 
      notifyObservers(response); 
      DoSomethingElse(); 
      String response = "Doing something else"; 
      setChanged(); 
      notifyObservers(response); 
    } 
    catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
private void DoSomething(){ 
} 
private void DoSomethingElse(){ 
} 


public class MainActivity{ 
public class ResponseHandler implements Observer { 
    private String resp; 
    public void update (Observable obj, Object arg) { 
     if (arg instanceof String) { 
      resp = (String) arg; 
      //Write message to UI here ie System.out.println("\nReceived Response: "+ resp); 
      //or EditText et = (EditText)findViewById(R.id.blah); 
      // blah.SetText(resp); 
     } 
    } 
} 
private void doStuffAndReportToUI(){ 
    final WorkerThread wt = new WorkerThread(); 
    final ResponseHandler respHandler = new ResponseHandler(); 
    wt.addObserver(respHandler); 
    Thread thread = new Thread(wt); 
    thread.start(); 
} 
5

有很多方法可以做到這一點,使用AsyncTask or Threads。簡短的回答。

提示:用戶界面的東西可以在預postExecute/runOnUiThread/Handler類

9

要麼使用Handler,或者使用下面的代碼

runOnUiThread(new Runnable() 
    {   
     @Override 
     public void run() 
     { 
      // Ui Stuff here     
     } 
    }); 
0

我試過+ tmho的答案,但它仍然給這個錯誤:

E/AndroidRuntime(****): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

我終於結束了+ ingsaurabh方式combinning它,像:

private class ResponseHandler implements Observer, Runnable { 

    Activity act; 

    public ResponseHandler(Activity caller) { 
     act = caller; 
    } 

    @Override 
    public void update (Observable obj, Object arg) { 
     act.runOnUiThread(this); 
    } 

    @Override 
    public void run() { 
     //update UI here 
    } 
} 

謝謝你們倆。