2014-07-13 49 views
0

開始一個新的活動,我需要從一個線程調用類新的活動是這樣的:
Intent i = new Intent(getContext(),GameOver.class);
,當我打電話startActivity(i)它給了我一個錯誤說,該方法是不確定我的課。
任何人都可以告訴我如何解決這個問題?
謝謝!
這裏是線程的完整運行方法:從一個線程

/*starts running the thread*/ 
    @Override 
    public void run(){ 
     while(run){ 
      Canvas c = null; 
      try { 
       c = surfaceHolder.lockCanvas(null); 
       synchronized (surfaceHolder) { 
        if (mode == STATE_RUNNING){ 
         /*if user has no more lives, he lost*/ 
         if(Global.lives == 0) lose(); 
         doDraw(c); 
        } 
       } 
      } finally { 
       // do this in a finally so that if an exception is thrown 
       // during the above, we don't leave the Surface in an 
       // inconsistent state 
       if (c != null) { 
        /*unlocks the canvas and shows the image drawn by the doDraw method*/ 
        surfaceHolder.unlockCanvasAndPost(c); 
       } 
      } 

哪裏lose();是誰的代碼是在啓動(意向)的方法。

+0

請發表您的完整代碼 –

+0

發送廣播或移動處理的新活動開始到主線程的邏輯 – EpicPandaForce

+0

我想這樣做,但也許有一個更簡單的方法。 – Pavle37

回答

0

首先,startActivity Contex的是一個方法,所以你需要通過引用一個有效的上下文..

第二件事情是,是,就我所知,活動只能從主開始(GUI)線程。有幾種方法如何做到這一點,其中之一是例如這樣的事情:

Handler handler = new Handler(Looper.getMainLooper()); 

handler.post(new Runnable() { 
    @Override 
    public void run() { 
     Intent intent = new Intent (MyActivity.this, NextActivity.class); 
     startActivity(intent); 
    } 
}); 
+0

不,這不起作用,因爲我的課程沒有擴展活動。我需要通知來電者發生了一些事情,但我不想使用廣播接收器。 – Pavle37

+0

我認爲,在這種情況下,你有一個問題:-)你將需要一些上下文來開始新的活動:-)。如果您沒有機會傳遞上下文,那麼您需要在應用中的某個現有Activity或服務上使用靜態變量/函數來實現一些醜陋的解決方法,但這通常不是您真正想要的。 – tpcz

+0

服務類別如何?它在主線程中工作。 – Aleksandr