2017-02-26 21 views
-1

假設您有這個班級管理計時器。這只是一個測試。計時器上的Looper.prepare錯誤

package it.rockopera.scsremote; 
import android.content.Context; 
import java.util.Timer; 
import java.util.TimerTask; 

public class CueTimer extends Thread{ 
    private Context context; 
    private MainActivity main = new MainActivity(); 
    private Timer timer; 
    int elapsed = 0 ; 

    public CueTimer(Context c){ 
     context= c; 
     timer = new Timer(); 
     timer.schedule(new TimerTask() { 
      @Override 
      public void run() { 
       elapsed+=1000; 
       System.out.println("elapsed: " + String.valueOf(elapsed));     
      } 
     },0,1000); //Update text every second 
    } 
} 

我想從另一個調用類的這種方法是這樣的:

CueTimer cuetimer = new CueTimer(context); 
cuetimer.start() 

這裏的錯誤:

Process: it.rockopera.scsremote, PID: 7562 java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() at android.os.Handler.(Handler.java:200) at android.os.Handler.(Handler.java:114) at android.app.Activity.(Activity.java:789) at it.rockopera.scsremote.MainActivity.(MainActivity.java:47) at it.rockopera.scsremote.CueTimer.(CueTimer.java:32) at it.rockopera.scsremote.Client$Read_SCS_MSGs.run(Client.java:477) at java.lang.Thread.run(Thread.java:761)

我試圖尋找這個錯誤,但我可以」找到類似的東西。 謝謝!

+1

你能給出CueTimer的完整類代碼,以及你從哪裏調用cuetimer.start()的類嗎? –

+0

'main = new MainActivity();'你不能自己創建活動的實例。把它留給系統。 – njzk2

+0

我評論main = new MainActivity();因爲它沒有用在這個方法 –

回答

0

每個新線程應該調用Looper.prepere()如果你想使用Handler

Threads by default do not have a message loop associated with them; to ?create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.

但在這行代碼中的實際問題:

private MainActivity main = new MainActivity(); 

有實際上是兩個問題。首先 - 看起來像不是在主線程上創建CueTimer而不是在主線程上導致MainActivity的實例化。其次 - 絕對不要直接實例化活動。您的活動應在AndroidManifest.xml註冊並通過Intent訪問。

+0

我評論私人MainActivity main = new MainActivity();因爲它不用於CueTimer方法。 –

+0

我應該在建議的代碼中調用Looper.prepare()? –

+0

由於手動創建「活動」,您提出的代碼無效。如果你消除了這一點 - 你不需要調用'Looper.prepare()'。 – j2ko