-2

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. 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();
}

}

Ajay Reddy
  • 107
  • 3
  • 2
    Quoting [the JavaDocs for `Service`](https://developer.android.com/reference/android/app/Service.html): "A Service is not a thread" and, in [the JavaDocs for `onStartCommand()`](https://developer.android.com/reference/android/app/Service.html#onStartCommand(android.content.Intent,%20int,%20int)): "Note that the system calls this on your service's main thread... You should always avoid stalling the main thread's event loop. When doing long-running operations, network calls, or heavy disk I/O, you should kick off a new thread". You have not started a thread, so your work is freezing your UI. – CommonsWare Oct 10 '17 at 23:43

1 Answers1

0

Use Handler or seperate background thread to finish your long work. once you are done,post the value on UI thread.

Btw, on Android O +, the service would only run as long as your app is alive. As soon as your app goes in background, the app will shut down the service. Consider using JobScheduler

Akshay
  • 806
  • 11
  • 26