[英]Running a background service android without freezing the UI
I need to log "Some text" in the devices storage after every 5 minutes can some one point me to the best way to do this.我需要每 5 分钟后在设备存储中记录“一些文本”,有人可以指出我这样做的最佳方法。 But i do not want the main thread to freeze and the logging thread should be alive all the time.
但是我不希望主线程冻结并且日志记录线程应该一直处于活动状态。 I tried this but it seems to freeze my emulator is there a better way to do the same
我试过了,但它似乎冻结了我的模拟器是否有更好的方法来做同样的事情
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();
}
} }
Use Handler
or seperate background thread to finish your long work.使用
Handler
或单独的后台线程来完成你的长期工作。 once you are done,post the value on UI thread.完成后,将值发布到 UI 线程上。
Btw, on Android O +, the service would only run as long as your app is alive.顺便说一句,在 Android O + 上,只要您的应用程序处于活动状态,该服务就会运行。 As soon as your app goes in background, the app will shut down the service.
一旦您的应用程序进入后台,该应用程序将关闭该服务。 Consider using JobScheduler
考虑使用 JobScheduler
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.