سؤال

I'm writing an application that streams RTSP to a server. With the 'NetworkOnMainThreadException', I need to perform all network communication on a separate thread. I know that AsyncTask is a somewhat simplified way of performing network operations on a separate thread. However, its interface is also limited (communication between main and asynctask). Also, logically, it seems that it shouldn't be used for long-running tasks.

There is Thread Runnable backed option. It is more flexible and complicated.

Does it make sense to implement a client with AsyncTask or should I stick with Thread Runnable?

هل كانت مفيدة؟

المحلول

For long running operations you should use a Thread. An AsyncTask is the best option for short tasks which only take a few seconds and are initiated directly be the user. A use case for an AsyncTask would be loading data from a web service on demand. A use case for a Thread would be a long running connection between some server and a client over which data is exchanged continuously. So to summarize, reasons to use an AsyncTask:

  • Task only takes a few seconds
  • The task is initiated directly by the user e.g. through a Button.
  • The user receives feedback about the progress through a ProgressBar or some other indicator

And reasons to use a Thread:

  • The task takes a long period of time to execute or has no predefined end e.g a server listening for connections
  • The task runs in the background without the users knowledge
  • The task runs independent from the UI with only minimal feedback.

You have to decide which option to use, both have advantages and disadvantages. But your question sounds like a Thread may be of better use to you. If you have any additional questions feel free to ask.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top