我正在製作Android遊戲時出現了問題。在這個遊戲中,「敵方太空船」將在隨機時間發射激光爆炸。因此,爲了做到這一點,我決定創建一個生成隨機數的方法,如果生成的數字是4,那麼將填充LaserBlasts的ArrayList。線程中的方法調用給出了「無法在線程中創建處理程序」異常
這裏是方法:
// generates random number which later is used to decide if shoot ot not
public static void generateRandomNumber(ArrayList<EnemyShipLaserBlast> listOfLaserBlasts) {
Random random = new Random();
int number = random.nextInt(30);
switch (number) {
case 1:
break;
case 2:
break;
case 3:
listOfLaserBlasts.add(new EnemyShipLaserBlast(5, 3));
Log.i("LASER BLAST WAS ADDED", "**************");
Log.i("size laser blasts " + listOfLaserBlasts.size(), "--------");
break;
case 4:
break;
}
然而,當我把這種方法從run()
方法(這是由線程中運行),我得到一個
了java.lang.RuntimeException:能在線程中創建處理程序, 尚未調用Looper.prepare()。
我run()
方法是這樣的:
@Override
public void run() {
int frames = 0;
long startTime = System.nanoTime();
long currTime = 0;
long lastTime = System.nanoTime();
while (playing)
{
currTime = System.nanoTime();
update((currTime - lastTime)/ 1000000000.0f); //updates the game data
draw(); //draws the screen based on the game data
control(); //controls how long is it until the run() method is called again
lastTime = currTime;
frames = frames + 1;
if (System.nanoTime() - startTime > 100000000)
{
framesPerSecond = frames;
frames = 0;
startTime = System.nanoTime();
}
}
}
所以我想問問你們,如果我應該把這個方法在其他地方也許還有另一種途徑來解決這樣的問題呢?
請編輯您的問題併發布**整個**堆棧跟蹤。 – CommonsWare
如果我們能夠看到你創建'Thread'和'Handler'的代碼,它也會有所幫助。 – clownba0t
我編輯了我的答案,希望它會有所幫助。 –