Reputation: 107
I've been working on an app to send sensor data via UDP. I have implemented a UDP client with an AsyncTask, and have created a Timer to execute this AsyncTask (send UDP packets) at a fixed interval.
However, I've noticed that there is intermittent lag in outputting udp packets, indicating that the scheduled executions are being held up at times. I've noticed that if I play with the UI (slide the notification bar up and down/have a notification pop up), the scheduled executions are held up.
This leads me to wonder if the Timer is indeed running on a background thread or not? The developer docs seem to indicate that it does, however it seems to get held up with UI events.
My code is below, perhaps there is an issue with my implementation? My app is currently listening for sensor data, and outputting accel in X direction via udp. I am receiving the packets on a simple python server.
// code omitted
Upvotes: 1
Views: 1487
Reputation: 12327
As mentioned above, you are doing too much work on your UI thread. I would approach this by running a Service in the background and then starting/stopping the service via the Activity. Understand that basic Service
class also uses the UI thread so you should do your work in a thread in the Service. You could look into using the IntentService class as it encapsulates the workflow of creating a worker thread for you.
Upvotes: 1
Reputation: 36
Problem:
I think the lag is caused by the amount of work being done on your applications main thread (the UI thread).
Your registering all your listeners in onCreate(), which places them on the main thread. Since your registering for updates at the frequency of SENSOR_DELAY_NORMAL, your listener is trying to handle 3 new sensor events every ~200 milliseconds. The lag is more noticeable when you play with the UI because UI listeners are also registered on the main thread.
Solution:
One way to solve this would be to listen to the sensor updates on a separate thread. Try using a HandlerThread; use its looper to create a handler on a separate thread, which you can then use when registering the listeners. This is a good example of how to use it!
Upvotes: 2