background task Works all the application life... Android - android

it is logical question so I don't have code.
My question is:
How may I run background task that make Network work (waiting for messages from the server) and in the same time updates the UI when Message arrive!!
the Paradox "Android prevent access to UI from another nonUI thread", and "prevent network accesss from UI thread!!!"
Important: I want to run my method all the time that the application run, and scan network buffers and when I get message I want to update the UI and messages List...

That sounds like a perfect description for a Service. You can use IntentService or build your own Service (be careful, the last one doesn't start in a new thread by default).
There are also many examples out there how to update the UI from a Service (i.e. using Notifications or Broadcast).

Android provides built in class to perform network operation. For this purpose you can use AsyncTask class.
AsyncTask enables proper and easy use of the UI thread. This class
allows to perform background operations and publish results on the UI
thread without having to manipulate threads and/or handlers.
You can get details from here Android AsyncTask
But if you want to check message continuously then Service is the best solution as #AlexS explained it perfectly.

Related

What is the difference between thread and service in android , when downloading an image

What is the difference between thread and service in android,when downloading an image
There are lots of difference between Normal thread and a Service
Service: Due to android component it runs on UI thread but without any view shown to user. It runs in background with the same kind of property that an activity have, like you cannot run network operations (downloading image, calling web service) in service for that you have to use Thread which will run on worker thread other than UI thread.
Thread: Its an independent path of execution which can consist network operation, complex coding, huge amount of data transfer and accept. Thread is not related to android but in android it is used to perform different task. You can download an image on Thread but to show it on any UI part you have to update downloaded image on UI thread using runOnUIThread method
Please let me know if this explanation clears your doubt. If not let me know which part you did not understand and what exactly is your question.
With rare exceptions, you should never explicitly create a Thread. Threads are expensive and prone to programmer error. Use AsyncTask because it handles the complexity of thread safety and provides the optimization of thread pooling. Or better yet, if network activity is your reason for doing work outside the main thread, use one of the many network libraries that manages all of these concerns for you. Which approach is fastest is not something that can be answered generally, and should never even be a concern until you've tried the simple and clear solution and demonstrated that its performance is inadequate.
Regardless of how you make your network activity asynchronous, any network activity that is not started and completed (or cancelled) within the lifetime of a single Activity instance needs to be hosted in something else. If it only needs to survive across configuration changes, host it in a retained Fragment. If it needs to survive between different activities, host it in a Service. When choosing between these options, remember that your Activity may be destroyed any time it goes into the background or backstack.

Async task or threads

I have the following task:
I have to do a Wi-Fi scan and then send some RSSs to the a server to obtain a location from the server. After that I should display the location on a map.
I have one activity in my application. What is the best way to implement it? I haven't implemented a thread nor AsyncTask in android before. So I don't know a lot about it. I have read about threads and AsyncTask on android developer website. But I still can't understand everything.
I would appreciate it if anyone can tell me when its the best to use threads, and how AsynTask is different from threads and when to use AsyncTask instead of threads.
EDIT: the task that I have to implement should run only when the user click on actioBar item
.
If you can't understand the read documentation, I'd suggest starting with an AsyncTask, as it already implements a Thread when doInBackground() is fired and it already implements some mechanisms that you would probably have to implement by hand when using Threads (concurrency, Thread start/stop processes, sending information to UI thread, ...).
However, you don't specify what exactly want to do. If you plan to do a long-running process, instead of Threads or AsyncTasks, it's recommended using Service that would start a Thread as implementation, as contrary to popular beliefs, AsyncTasks are meant for short-lasting tasks.
In any case, if you're starting with this, I'd recommend using AsyncTask first, and when understood what it's doing and how, decide by yourself what's the best way to implement what you're planning to do: if running a Service with a Thread inside, a Thread itself or an AsyncTask.

Separate Threads for UI and Logic - Android

I want to create separate threads for implementing the core logic and updating the GUI.
Both threads should not share data with them directly. For this, i want to create a vector queue with synchronized get() and put() methods.
Suppose if an onClick event happens in the GUI thread, it notifies the core thread that it received the OnClick event. So the core thread implements something and puts the result in the vector. At this point, the GUI thread is notified of the received result and it fetches it and updates the screen.
I cant figure out how to do this. Is there a way this could be implemented?
You can do that as you would in any other framework or environment. The Android api offers you a lot of high level ways of handling multithreaded applications like you described (AsyncTask, Handler/Thread/Runnable, etc), but you can also wrap these in your own processing queue. I've done that recently where I created a logical queue for processing, and when I push something to the queue, I run a method that checks my queue for items and processes them on a background thread. You can notify the system when your processing is complete by sending broadcast intents and registering IntentFilters at the Activity level (don't forget to unregister) or you can implement your own listener interfaces the way the Android UI framework does with UI events on Views
At the heart of it though, however you wrap it, AsyncTask makes it really easy to call back and forth between background threads and the main UI thread. onPreExecute, onProgressUpdated and onPostExecute all run on the UI thread and doInBackground runs in a background thread that is automatically created for you. Doesn't get any easier than that

Android Thread & ASynTask

I want to implement the thread in my application
first requirement is:
Each activity access the local database that time it take some time to load.So I am planning to give progress-dialog.I want to do it in thread.Currently I did using the AsynsTask because of I dodnt know how long will take for record. Other than AsynsTask How we can implement using Thread?
Multitasking Facility :
I want to run two activity.One is in background.I.E If there are any upload available(Database Syn Android to SQL Server) while running activity ,Upload should start in background.How we can implement this?
Please guide me on this
Thanks in advance
You want to synchronize your database in background so I think you have to use service in which you have to implement thread and you have to write your code in thread.
You can then schedule your service startup time and also you can repeat your service when ever you want to keep duration for start service.
And for upload you have to options
1) Using AysncTask
2) Using Service with thread
And also know that Service is running in main UI so if you want to use service for synchronize database you have to implement thread
you can execute many AsyncTasks in the background, but only one Activity can be active at a single time.
AsyncTask handles the threading for you.
In your case, AysncTask has one benefit, that when multi-user (other word, multi connection) connect to database, AsyncTask will do in serial. (But you should notice, this might change through android version, for example: at Donut, they will do together, but in Honeycomb to now, serially)

Handler vs AsyncTask

I'm confused as to when one would choose AsyncTask over a Handler. Say I have some code I want to run every n seconds which will update the UI. Why would I choose one over the other?
IMO, AsyncTask was written to provide a convenient, easy-to-use way to achieve background processing in Android apps, without worrying too much about the low-level details(threads, message loops etc). It provides callback methods that help to schedule tasks and also to easily update the UI whenever required.
However, it is important to note that when using AsyncTask, a developer is submitting to its limitations, which resulted because of the design decisions that the author of the class took. For e.g. I recently found out that there is a limit to the number of jobs that can be scheduled using AsyncTasks.
Handler is more transparent of the two and probably gives you more freedom; so if you want more control on things you would choose Handler otherwise AsynTask will work just fine.
My rule of thumb would be:
If you are doing something isolated related to UI, for example downloading data to present in a list, go ahead and use AsyncTask.
If you are doing multiple repeated tasks, for example downloading multiple images which are to be displayed in ImageViews (like downloading thumbnails) upon download, use a task queue with Handler.
Always try to avoid using AsyncTask when possible mainly for the following reasons:
AsyncTask is not guaranteed to run since there is a ThreadPool base and max size set by the system and if you create too much asynctask they will eventually be destroyed
AsyncTask can be automatically terminated, even when running, depending on the activity lifecycle and you have no control over it
AsyncTask methods running on the UI Thread, like onPostExecute, could be executed when the Activity it is referring to, is not visible anymore, or is possibly in a different layout state, like after an orientation change.
In conclusion you shouldn't use the UIThread-linked methods of AsyncTask, which is its main advantage!!! Moreover you should only do non critical work on doInBackground.
Read this thread for more insights on this problems:
Is AsyncTask really conceptually flawed or am I just missing something?
To conclude try to prefer using IntentServices, HandlerThread or ThreadPoolExecutor instead of AsyncTask when any of the above cited problems ma be a concern for you. Sure it will require more work but your application will be safer.
If you want to do a calculation every x seconds, you should probably schedule a Runnable on a Handler (with postDelayed()) and that Runnable should start in the current UI thread. If you want to start it in another thread, use HandlerThread.
AsyncTask is easier to use for us but no better than handler.
The Handler is associated with the application’s main thread. it handles and schedules messages and runnables sent from background threads to the app main thread.
AsyncTask provides a simple method to handle background threads in order to update the UI without blocking it by time consuming operations.
The answer is that both can be used to update the UI from background threads, the difference would be in your execution scenario. You may consider using handler it you want to post delayed messages or send messages to the MessageQueue in a specific order.
You may consider using AsyncTask if you want to exchange parameters (thus updating UI) between the app main thread and background thread in an easy convinient way.
AsyncTask presumes you will do something on the UI thread, after some background work is finished. Also, you can execute it only once (after this, its status is FINISHED and you'll get an exception trying to execute it once more). Also, the flexibility of using it is not much. Yes, you can use THREAD_POOL_EXECUTOR for a parallel execution, but the effort might be not worthy.
Handler doesn't presume anything, except handling Runnables and Messages. Also, it can be run as many times as you wish. You are free to decide to which thread it must be attached to, how it communicates with other handlers, maybe produce them with HandlerThread. So, it's much more flexible and suitable for some repeated work.
Check different kind of Handler examples here.
They are best interview question which is asked.
AsyncTask - They are used to offload of UI thread and do tasks in background.
Handlers - Android dosent have direct way of communication between UI and background thread. Handlers must be used to send message or runnable through the message queue.
So AsyncTasks are used where tasks are needed to be executed in background and Handlers are used for communication between a UI and Background Thread.
doInBackground - basically does work in another thread.
onPostExecute - posts the results on the UI thread and it is internally sending message to handler of main thread. Main UI thread already has a looper and handler associated with it.
So basically,if you have to do some background task,use AsyncTask. But ultimately,if something needs to be updated on UI,it will be using main thread's handler.

Categories

Resources