2011-08-01 121 views
0

我想找到一種方式,該線程可以關閉並重新啓動,而不會程序崩潰。它從一個菜單中調用,一個activity將面板設置爲它的內容視圖,我希望當在android上按下返回箭頭時,它返回到活動,然後該線程可以重新啓動,但是目前我嘗試的任何變體都會導致它墜毀在一個點或另一個:(安卓/ java線程崩潰

package SortItOut.sortitout; 

import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Canvas; 
import android.view.MotionEvent; 
import android.view.SurfaceHolder; 
import android.view.SurfaceView; 

public class Level1Panel extends SurfaceView implements 
SurfaceHolder.Callback { 

private Level1Thread thread; 
static Bitmap background; 
static int x = 0; 

public Level1Panel(Context context) { 
super(context); 
getHolder().addCallback(this); 
background = BitmapFactory.decodeResource(getResources(), R.drawable.gamebackground); 
thread = new Level1Thread(getHolder(), this); 
setFocusable(true); 
} 


public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { 
} 

public void surfaceCreated(SurfaceHolder holder) { 
thread.setRunning(true); 
thread.start(); 
} 


public void surfaceDestroyed(SurfaceHolder holder) { 
thread.stop(); 
} 

public void render(Canvas canvas) 
{ 
canvas.drawBitmap(background, x, 0, null); 
x = x + 20; 
} 

} 

======主題=======

package SortItOut.sortitout; 

import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Canvas; 
import android.view.SurfaceHolder; 

public class Level1Thread extends Thread { 


private boolean running; 
private SurfaceHolder surfaceHolder; 
private Level1Panel gamePanel; 


public void setRunning(boolean running) { 
    this.running = running; 
} 

public Level1Thread(SurfaceHolder surfaceHolder, Level1Panel gamePanel) { 
    super(); 
    this.surfaceHolder = surfaceHolder; 
    this.gamePanel = gamePanel; 
    } 



public void run() { 
    Canvas canvas; 

    while (running) { 
    canvas = null; 

    try { 
     canvas = this.surfaceHolder.lockCanvas(); 
     synchronized (surfaceHolder) { 
     this.gamePanel.render(canvas); 

     } 
     } finally { 

    if (canvas != null) { 
     surfaceHolder.unlockCanvasAndPost(canvas); 
     } 
     } 
     } 
} 



} 
+0

你會得到某種異常嗎? – Kiril

回答

0

你不應該使用thred.stop();你必須允許通過停止它內部的循環,使其自行停止。

檢查第二個例子SurfaceView aniamtion電子:How can I use the animation framework inside the canvas?

+0

我在表面破壞方法下的這個鏈接中實現了代碼。以前的活動不再崩潰,但重新啓動線程沒有影響 –

+0

例如,如果我重新啓動線程,黑屏顯示,而不是運動圖像 –

+0

我認爲這可能是因爲您使用的是靜態X,它積累了價值並保留了活動的破壞。嘗試放置x = 0;在構造函數「公共Level1Thread(SurfaceHolder ...)」 – Lumis

0

這裏有一些建議(沒有得到崩潰之外的任何細節):

  • 你應該Implement Runnable instead of Extend Thread
  • 你應該讓線程知道它應該退出循環。
  • 您應該interrupt()線程而不是調用stop()(中斷也使線程退出阻塞狀態)。
  • 您應該在run方法內處理InterruptedException
  • 當你被打斷時,你應該優雅地退出(即完成你正在做的和清理的任何事情)。

我敢肯定我錯過了一些事情,但通常這應該讓你擺脫困境。再說一遍,在不知道你遇到的特定異常的情況下,我會假設你正在調用stop,並且線程在運行時無論在什麼狀態下都沒有正確清理,因此你會在某個點或另一個點上崩潰(取決於什麼是國家損壞)。