我创建了一个带有asynctask的文件。然后安排执行程序每隔一秒向所述文件写入一次信息。一旦我触摸一个按钮,执行程序就会关闭并且文件已关闭,但文件中通常没有写入任何文件。
代码:
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
preferences.edit().putBoolean(GlobalConstants.stopPreference,false).commit();
loc_thr = new LocationThread(preferences, getApplicationContext());
loc_thr.run();
startButton.setVisibility(View.INVISIBLE);
startButton.setClickable(false);
stopButton.setVisibility(View.VISIBLE);
stopButton.setClickable(true);
currentDateAndTime = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
fileName = getString(R.string.loc_log_path) + currentDateAndTime + ".txt";
new CreateFileTask(fileName).execute();
loc_file = new File(fileName);
try {
FOS = new FileOutputStream(loc_file.getAbsolutePath());
OSW = new OutputStreamWriter(FOS);
OSW.write(GlobalConstants.fileHeader + '\n');
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
scheduledTaskExecutor = Executors.newScheduledThreadPool(5);
scheduledTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
if(loc_thr.getLocationStatus() & loc_thr.newLocation() & !preferences.getBoolean(GlobalConstants.stopPreference,false)){
SensorBundle SB = new SensorBundle(loc_thr.getCurrentLocation(),loc_thr.getCurrentGPSStatus());
try {
OSW.write(new SimpleDateFormat("yyyy/MM/dd;hh:mm:ss").format(new Date()) + ";");
OSW.write(SB.getLatitude() + ";");
OSW.write(SB.getLongitude() + ";");
OSW.write(SB.getAltitude() + ";");
OSW.write(SB.getAccuracy() + ";");
OSW.write(SB.getProvider() + ";");
OSW.write('\n');
} catch (IOException e) {
e.printStackTrace();
}
} else{
if(preferences.getBoolean(GlobalConstants.stopPreference,false)){
try {
OSW.close();
FOS.close();
scheduledTaskExecutor.shutdown();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}, 0, 1, TimeUnit.SECONDS);
}
});
每当按下停止按钮时,先前查询的SharedPreference将设置为true。
答案 0 :(得分:0)
我认为您的问题可能就在这里
new CreateFileTask(fileName).execute();
loc_file = new File(fileName);
我假设此任务创建了该文件,并且您希望在new File(fileName)
文件已经创建时。这是否真实是不确定的。如果AsyncTask CreateFileTask被安排在下一个语句执行之前运行并完成,那么该文件将在那里,否则它不会。您是否在IOlogception或FileNoteFoundExceptions中看到了logcat中的堆栈跟踪?