我正在尝试编写一个简单的活动,该线程每 N 秒在文本文件中写入一个值。
问题是,在我运行活动几分钟后,在手机处于待机状态的情况下,线程有时会停止更长的时间,甚至几分钟。
在 Run() 中,我必须写入文件而不是睡眠 N 秒。
public void run() {
isrunning = true;
int cont=0;
try {
while (isrunning)
{
es.writeSD("- THREAD:" + cont, true);
Thread.sleep(1000);
es.writeSD("- THREAD - sending: " + cont,true);
cont++;
}
}
catch (InterruptedException e) {
es.writeSD("- THREAD - InterruptedException: " + e.getMessage(),true);
}
catch (Exception e) {
es.scriviSD("- THREAD - Exception: " + e.getMessage(),true);
}
}
这是带有时间戳的日志
20130911T154448 : - 螺纹:36
20130911T154449 : - 线程发送: 36
20130911T154449 : - 螺纹:37
20130911T154652 : - 线程发送: 37
20130911T154652 : - 线程:38
20130911T154656 : - 发送线程: 38
您需要强制设备保持唤醒状态。但要小心,这会很快耗尽电池电量!
PowerManager
的WakeLock
正是您所需要的:https://developer.android.com/reference/android/os/PowerManager.WakeLock.html
启动线程时,acquire()
WakeLock
,完成后release()
它。
public void run() {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
isrunning = true;
int cont=0;
try {
while (isrunning) {
es.writeSD("- THREAD:" + cont, true);
Thread.sleep(1000);
es.writeSD("- THREAD - sending: " + cont,true);
cont++;
}
} catch (InterruptedException e) {
es.writeSD("- THREAD - InterruptedException: " + e.getMessage(),true);
} catch (Exception e) {
es.scriviSD("- THREAD - Exception: " + e.getMessage(),true);
} finally {
wl.release();
}
}