我是android编程的新手。我编写了一个应用程序,它读取传感器数据(陀螺仪和加速度计),并且在传递值时应该做一些事情。sensor_delay_fastest
现在我的问题是电池只运行一小时,和之间没有区别sensor_delay_game
。是否有可能关闭屏幕灯以节省能源,或者我应该将此应用程序作为服务运行还是有另一种可能性?我也试过SCREEN_DIM_WAKE_LOCK
,没有明显效果。
感谢帮助
贡纳尔
您可能将电池消耗归咎于错误的罪魁祸首。电池消耗的最大恶棍不是在您的主应用程序循环中使用 Thread.sleep(int ms)。
您的主循环可能每秒运行数千次,而实际上实施帧限制可以将数量减少到 24-60(对于流畅的动画),或者对于非常基本的应用程序甚至可以低至 10-20。
考虑一下:如果你不让你的线程休眠,你实际上是在让你的应用程序(和主循环)尽可能快地运行尽可能多的次数。如果没有睡眠,您的应用程序会消耗 100% 的可用资源来运行,即使它实际上什么也没做。
这是一个很好的入门教程,这是一个实现示例(来自链接)。不要紧张它有多长;没有评论,它要短得多...
public void run() {
Canvas canvas;
Log.d(TAG, "Starting game loop");
// initialise timing elements for stat gathering
initTimingElements();
long beginTime; // the time when the cycle begun
long timeDiff; // the time it took for the cycle to execute
int sleepTime; // ms to sleep (<0 if we're behind)
int framesSkipped; // number of frames being skipped
sleepTime = 0;
while (running) {
canvas = null;
// try locking the canvas for exclusive pixel editing
// in the surface
try {
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
beginTime = System.currentTimeMillis();
framesSkipped = 0; // resetting the frames skipped
// update game state
this.gamePanel.update();
// render state to the screen
// draws the canvas on the panel
this.gamePanel.render(canvas);
// calculate how long did the cycle take
timeDiff = System.currentTimeMillis() - beginTime;
// calculate sleep time
sleepTime = (int)(FRAME_PERIOD - timeDiff);
if (sleepTime > 0) {
// if sleepTime > 0 we're OK
try {
// send the thread to sleep for a short period
// very useful for battery saving
Thread.sleep(sleepTime);
} catch (InterruptedException e) {}
}
while (sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS) {
// we need to catch up
this.gamePanel.update(); // update without rendering
sleepTime += FRAME_PERIOD; // add frame period to check if in next frame
framesSkipped++;
}
if (framesSkipped > 0) {
Log.d(TAG, "Skipped:" + framesSkipped);
}
// for statistics
framesSkippedPerStatCycle += framesSkipped;
// calling the routine to store the gathered statistics
storeStats();
}
} finally {
// in case of an exception the surface is not left in
// an inconsistent state
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
} // end finally
}
}