-2
我需要每5分鐘後,登錄到設備存儲「一些文本」可有人點我做到這一點的最好辦法。 但我不想讓主線程凍結和記錄線程應該是活着的時間。 我試過,但它似乎凍結我的模擬器 有沒有更好的方式做同樣的運行後臺服務的Android不凍結UI
public class DataWriteService extends Service {
private FileIOHelper fileHelper= new FileIOHelper("Test.txt");
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Gets location and writes to a file
fileHelper.writeToFile(this, "Some text");
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
引用[用於'Service'所述的JavaDoc](https://developer.android.com/reference/android/app/Service.html): 「A服務不是線程」,並在[該對於'onStartCommand()'](https://developer.android.com/reference/android/app/Service.html#onStartCommand(android.content.Intent,%20int,%20int))的JavaDoc:「需要注意的是該系統調用此對您的服務的主線程...你應該總是避免拖延主線程的事件循環。當進行長時間運行的操作,網絡電話,或者大量的磁盤I/O,你應該啓動新線程」。你還沒有開始線程,所以你的工作正在凍結你的UI。 – CommonsWare