2012-10-04 18 views
1

我正在製作一個角色RPG風格的遊戲,我希望角色的當前健康狀況每隔一段時間都會增加,直到其完全健康。在啓動時運行應用程序的整個生命週期的Android線程

我搜索了很多文章和帖子,我似乎無法找到任何要做的事情。我的想法是在擴展Application的全局var類中創建一個Thread或Handler。

我使用

@Override 
public void onCreate() 
{ 
    super.onCreate(); 
    thread = new Thread() { 
     public void run() { 
      // do something here 
      System.out.println("GlobalVars - Sleeping"); 
      handler.postDelayed(this, 10000); 
     } 
    }; 
    thread.start(); 
} 

那裏,而不是僅僅印刷,我會讓我的函數調用。這是完成這個的好方法嗎?我可以爲這個線程實施onPause和onResume嗎?當應用程序被電話打斷,或者他們點擊主頁按鈕?

謝謝

回答

0

您不需要(或想要)另一個線程爲此。反而從時間計算健康。

long health = 1; // about to die 
long healthAsOf = System.currentTimeMillis(); // when was health last calculated 
long maxHealth = 100; // can't be more healthy than 100 
long millisPerHealth = 60*1000; // every minute become 1 more healthy 

public synchronized long getHealth() { 

    long now = System.currentTimeMillis(); 
    long delta = now-healthAsOf; 
    if(delta < millisPerHealth) return health; 
    long healthGain = delta/millsPerHealth; 
    healthAsOf += millsPerHealth * healthGain; 
    health = Math.min(maxHealth, health+healthGain); 
    return health; 

} 

public synchronized void adjustForPause(long pauseMillis) { 

    healthAsOf += pauseMillis; 

} 

PS:你可能想在每個幀的開始搶時間只有一次,使畫面不會有事情的時間略有不同回事。

相關問題