Answer the question
In order to leave comments, you need to log in
Network thread?
The task was to develop a network application for Android. Previously, I have not come across Java or Android, do not judge strictly.
Network operations in the main thread cannot be performed, an exception pops up. OK. I create a class that implements the Runnable interface. I create a new thread based on it. I receive data in a loop. And how to transfer the data back to the main stream? And how to send a message from the main thread to the network thread? Own solution is to use queues. But I'm not sure if this is thread-safe. Maybe there is some more elegant solution?
Answer the question
In order to leave comments, you need to log in
Will the network stream be constant, or will it be launched at the click of a button, or does it need to be launched after a certain time interval?
If it should be constantly in the background, then do Service. You can transfer something from the UI thread to it and vice versa receive it back.
There is a good article about services in more detail - read here
If at the click of a button, then use AsyncTask. Importantly, you will not be able to update UI elements from other threads, so when you get some data, for example, you need to update the list of tweets, use the runOnUiThread (Runnable action) method, all activities have this method.
But AsyncTask is suitable for small operations, picking up a bunch of tweets or picking up rss - not long operations.
Using ExecutorServiceFor example, you can implement
Producer - Consumer. Erase in this screencast how.
If there are several activities, how will you fumble the queue between them? Here, either make a service in the background or initialize a queue in the Application class, it will be available to all activities, although I can’t say for sure if it’s a good idea to store a queue there, I’m most interested.
I understand that it's been two years.
It's better to do this:
The main thread checks the child threads and keeps track of their state.
All functionality lives in children.
The transfer between adjacent child threads will be created via a separate class.
And the most important thing is to synchronize streams, because the processing speed is higher than the network transmission speed.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question