-2

我需要每 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();
}

}

4

1 回答 1

0

使用Handler或单独的后台线程来完成您的长期工作。完成后,将值发布到 UI 线程上。

顺便说一句,在 Android O + 上,只要您的应用程序还活着,该服务就会运行。一旦您的应用程序进入后台,该应用程序将关闭该服务。考虑使用 JobScheduler

于 2017-10-11T00:05:50.580 回答