3

I would like to run a service that gets data from an external sensor and updates the UI every second without blocking the main thread. What is the most efficient possibility to make it? Thread, IntentService, Service? Or anyting else?

Thanks in advance!

Márió Posta
  • 153
  • 1
  • 7
  • Solution to your problem probably depends how you are getting data from external sensor. – Okas Oct 26 '17 at 13:03
  • I'm getting data via Bluetooth socket. I send a request and I get data. – Márió Posta Oct 26 '17 at 13:16
  • Then you already have a thread for this BT socket. Use the same thread and update UI with runOnUiThread as needed. – Okas Oct 26 '17 at 13:33
  • No, I don't have a permanent thread. A command looks like ResetTroubleCodesCommand clear = new ResetTroubleCodesCommand(); clear.run(sock.getInputStream(), sock.getOutputStream()); Then I get the data. So I need to execute these commands in a different thread. – Márió Posta Oct 26 '17 at 13:43
  • Maybe it would be better if you would post your code. – Okas Oct 26 '17 at 13:49

4 Answers4

2

You should use a binded service if you want to update UI regularly and the activity has to access the service method.

Service vs IntentService

Check how binded service in android works in this link

Vishal Yadav
  • 3,642
  • 3
  • 25
  • 42
Sharath kumar
  • 4,064
  • 1
  • 14
  • 20
1

I think you should use binding service.Read here.

Here are some examples:

  1. example1.
  2. example2
yashkal
  • 713
  • 5
  • 20
1

First off- Services run on the UI thread. So a service won't fix the problem of blocking the main thread. Of course getting a sensor reading is quick, so you shouldn't need to worry about it.

What else are you using the data for? If its only to update the UI, no need for a service. Just register for sensor events in your activity and update the UI when you get a sensor event. If you want to do something else, like save the data even when the app is in the background, then you may want to look at Services.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
0

JobScheduler should be used if your app targets Android 5.0 (API level 21) or later.

Nongthonbam Tonthoi
  • 12,667
  • 7
  • 37
  • 64