Allowing AsyncTask to Manipulate Values in Different Activity Classes
This title may seem strange, so let me try to explain what I'm trying to do. I have several activity classes, each representing a different view in my application. My initial activity class gets loaded when the application launches. The user enters values and eventually a TCP socket is opened, and I then use AsyncTask
to listen for and respond to messages from the server. I'd like for this AsyncTask
class to essentially listen until the app is closed/error condition reached, and be able to update values in other activity classes after they are started. Does this make sens开发者_如何学Ce (it's been a long, frustrating night)? I know that static activity class references are bad practice, and touching the UI thread from other activities is bad as well, but I'm having trouble finding a clean solution to this problem. Maybe using AsyncTask
is not the best approach here? Should I be using a service instead or something else entirely?
Thanks in advance.
The user enters values and eventually a TCP socket is opened, and I then use AsyncTask to listen for and respond to messages from the server.
AsyncTask
is designed for short-lived operations (e.g., flash reads, flash writes, Web service calls). Use your own background thread for indefinitely-long operations.
I'd like for this AsyncTask class to essentially listen until the app is closed/error condition reached
There is no such concept in Android of "app is closed", any more than there is a concept on the Web of "app is closed".
and be able to update values in other activity classes after they are started.
That sounds like a job for a service, not just some random thread or AsyncTask
. For starters, once your original activity that started the background thread or AsyncTask
is destroyed, you gotta gotta gotta get rid of the background thread or AsyncTask
.
Should I be using a service instead or something else entirely?
I would strongly recommend you look into services.
精彩评论