【发布时间】:2017-10-10 23:39:43
【问题描述】:
我需要在每 5 分钟后在设备存储中记录“一些文本”,有人可以告诉我执行此操作的最佳方法。 但我不希望主线程冻结,并且日志线程应该一直处于活动状态。 我试过了,但它似乎冻结了我的模拟器 有没有更好的方法来做同样的事情
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();
}
}
【问题讨论】:
-
引用the JavaDocs for
Service:“服务不是线程”,在the JavaDocs foronStartCommand():“请注意,系统会在服务的主线程上调用它......您应该始终避免停止主线程线程的事件循环。当进行长时间运行的操作、网络调用或大量磁盘 I/O 时,您应该启动一个新线程”。你还没有开始一个线程,所以你的工作正在冻结你的 UI。
标签: android multithreading service background android-task