V / s service AsyncTask

I am confused about the design of my application. I need to constantly poll the server to get new data from it. I am confused by the fact that it is better to use the Async Task option, launched at a fixed interval or when the service starts. The thread only starts when the application starts

+4
source share
5 answers

You already have the answers to your question, but I think this is worth the summary ...

What you need

If you want to run a piece of code that takes some time, you should always run it in a separate thread from the user interface thread.

There are two ways to do this:

Using Thread :

This is the easiest if you don’t need a lot of communication from the new thread to the user interface thread. If you need a message, you may have to use the Handler to do this.

Using AsyncTask :

It also works in a separate stream and already implements some communication channels with the user interface stream. Therefore, this option is preferable if you need this connection back to the user interface.

What you don't need

Service

This serves mainly to ensure that some code works even after exiting the main application, and it will work in the user interface thread if you do not create a new thread using the parameters described above. You said that your thread will be disconnected when you exit the application, so this is not what you need.

IntentService

This can be triggered by an external event (i.e. BroadcastReceiver ), which can run part of the code you define, even if your application is not running. Once again, based on your requirements, this is not what you are looking for.

Sincerely.

+5
source

a Android service is not in the background thread.

Therefore, you need to start a service that will start ASyncTask every time you want to poll.

Note that services, like other application objects, are started in the main thread of their hosting process. This means that if your service will do any intensive work with the CPU (for example, playing MP3s) or blocking (for example, network), it must create its own stream in which this work will be performed. More information on this can be found in the Processes and Threads section. The IntentService class is available as a standard implementation of the Service, which has its own thread, where it plans to do its job.

+2
source

Service should not be compared with AsyncTask . I think you most likely meant the IntentService here, and this is slightly different from Service , despite the common name.

Regarding periodic sampling, I would stick with a repeating alarm (using the AlarmManager ) and (most likely) use the IntentService to make the sampling.

Here you got the AsyncTask basics and some tutorials And here you got the IntentService basics and tutorials

Please note that IntentService jobs are queued by design, and AsyncTasks can work completely in parallel. However, keep in mind the regression associated with AsyncTask handling in the new APIs . Not as much as a workaround - these are just a few lines of code, however it's worth it to know this.

EDIT

The misunderstanding that many consider regarding the AsyncTask life cycle is related to the activity life cycle. This is WRONG . AsyncTask is independent of Activity. Finishing Activity does nothing for any AsyncTasks unless you clear them from onDestroy () with your code. However, if the activity process is killed when it is in the background, then AsyncTask will also be killed, since part of the entire process is killed

+1
source

If you want to "continuously poll", asyncTask will not do. The task stops when the application stops working with Android. The service itself will not do this, as Blundell has already pointed out. The service runs in the main thread, and you do not want to do polls in the main thread. There are two ways to do this: you create a Service that spawns its own thread to do what you want, or let it schedule polls that run in AsyncTask or in a separate thread. I try not to have a survey in my application, but if you need, creating a special stream in your service that makes the survey the best for me.

Depending on what your application does and what the survey does, you can give a separate thread a lower priority, so it does not interfere with other processing.

+1
source

The thread only starts when the application starts

Then AsyncTask will be the easiest solution. Periodically send data to the application stream using publishProgress() from the background stream. Set the desired spacing using Thread.sleep() in doInBackground() . Also, make sure that you start a new task in the onResume() Activity method and complete this task in the onPause() Activity method.

Example:

 public class MyActivity extends Activity { private AsyncTask<Void,String,Void> mAsyncTask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void onResume() { super.onResume(); mAsyncTask = new MyTask(); mAsyncTask.execute(); } @Override protected void onPause() { super.onPause(); if(mAsyncTask != null){ mAsyncTask.cancel(true); } } private void onServerResponse(String response){ Toast.makeText(this, "Got response !", Toast.LENGTH_SHORT).show(); } private final class MyTask extends AsyncTask<Void,String,Void>{ @Override protected Void doInBackground(Void... voids) { while (!isCancelled()){ String response = ""; //server query code here publishProgress(response); Log.i("TEST", "Response received"); //sleep for 5 sec, exit if interrupted ,likely due to cancel(true) called try{ Thread.sleep(5000); }catch (InterruptedException e){ return null; } } return null; } @Override protected void onProgressUpdate(String... values) { super.onProgressUpdate(values); if(values.length > 0){ onServerResponse(values[0]); } } } } 
0
source

Source: https://habr.com/ru/post/1442608/


All Articles