我编写了一个应用程序,用于记录来自智能手机传感器的数据。 我有一个线程每小时将这些数据写入文件。 当连接到我的笔记本电脑时,该应用程序工作正常。每个小时都会创建一个新文件。连接到笔记本电脑时的不同行为
但是,当智能手机与笔记本电脑断开时,它不会这样做。它不会崩溃,但应用程序运行整晚,只有一个文件被创建...
我的代码使用Thread.sleep()这是一个问题?
我测试这一个一个的Nexus 5采用Android 4.4.4
@Override
public void run()
{
String filename = "";
String directory = "";
Date now = new Date();
while (!stopped)
{
Log.i(TAG, "Start the one hour sleep");
sleepForOneHour(now);
now = new Date();
directory = directoryDateFormat.format(now);
filename = filenameDateFormat.format(now);
Log.i(TAG, "Write data to SD-card");
setFileWriteDirectory(directory);
writeDataToSdCard(filename);
}
super.run();
}
private void sleepForOneHour(Date filesWritten)
{
Date now = new Date();
long nowMillies = now.getTime();
long filesWrittenMillies = filesWritten.getTime();
long passedMillies = (nowMillies - filesWrittenMillies);
long milliesPerHour = (60 * 60 * 1000);
long waitMillies = (milliesPerHour - passedMillies);
try
{
sleep(waitMillies);
} catch (InterruptedException e)
{
Log.d(TAG, "Interrupted sleep in filehandler thread");
}
}
UPDATE
我尝试使用Android.Timer
代替Thread.sleep
,但是这给了相同的结果。