2012-10-04 19 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:你可能想在每个帧的开始抢时间只有一次,使画面不会有事情的时间略有不同回事。

相关问题