Run code in background, then update UI on completion - android

In my app I need to fetch some json data periodically from the internet, then I want to update the UI of my app based on this data. How can I execute a background task and then update the UI on completion? Here are some problems I ran into:
Using a service/alarm I can't send my json back to the activity
Using an timer/timertask I can't update the UI because only the thread that created the views may change them
Using asynctask was working fine but I cannot run it periodically
I have been implementing a listener in my activity that is triggered when the json has been fetched. This seems like a straight forward thing to do, I'm sure there must be a solution!

Using a service/alarm I can't send my json back to the activity, use binder to create connection between Service and Activity, or broadcast to transfer data to trigger ui update

Although adding a Binder between the Activity and the Service would have working, I ended up following resus's answer provided here. It uses a Handler to post a new task in the future in the method that is triggered by the AsyncTask's completion.
This worked well for me because I had already set up a listener.

Related

Getting data from server regularly even when the app is closed

I want to get data from the server and store it in a cache regularly, even when the app is closed. I am not sure what is the correct way to do it. I have listed down the possible ways I can think of. Please let me know the correct or the best way to do it. Really appreciate any help.
Create an Activity and set a repeated alarm to call a service. The service should connect to the server and download the data in cache.
From a fragment, check the last time the cache was updated and then if the data is out-dated, connect to server in a background thread and update the cache.
You can Directly Use IntentService for Frequently Updating Data
IntentService is a subclass of android.app.Service class. A stated intent service allows to handle long running tasks without effecting the application UI thread. This is not bound to any activity so, it is not getting effected for any change in activity lifecycle. Once IntentService is started, it handles each Intent using a worker thread and stops itself when it runs out of work.
IntentService would be an best solution, If you have an work queue to process. For example, if your application using analytics you will likely to send event name and related parameter to your tracking server for each user generated event. Although each event means a tiny piece of data, creating networking request on each click will result an overhead to your application
For implementation : Updating Data from Server Using Intent Serive
Do take a look at Android Sync Adapter Framework.
https://developer.android.com/training/sync-adapters/index.html
Hope this helps.

background task Works all the application life... 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.

android:How to get call backs from service to activity?

I am using a service to upload a file to server and I am getting some result after file uploaded I want some call backs from service like when upload completed, when got result, if didn't got result in specific time, when network lost etc. as per these call backs I need changes in my activity from where my service was called. currently I am using different-different broadcast send and receive like this.
Intent w = new Intent("<KEY>");
w.putExtra("***", ***);
sendBroadcast(w);
It is working fine now but I want to know that it is proper way to do such or is there any better way?
I also red about pass Handler from activity and pass message queue from service but I am not comfortable this.
Using BroadcastReceivers is perfectly fine.
But if your worker upload-thread needs to run once-off time, then an AsyncTask may better suits your needs. You do your work in doInBackground and then use onPostExecution() to update your GUI.
As you said, you can also use a Handler inside your Activity. But then your Service will need to be a bound Service in order for you to be able to pass the Handler to the Service.
For very simple things, I'd advise you to use an AsyncTask.

Android: Asynchronous process using AsyncTask for connecting to internet

For my Android app I need to call a web page from activity, and wait until a response is received from remote server. So I think I need to use a new thread. Can I use AsynkTask? How can I tell to my activity that it must wait for respose to AsynkTask process?
check asyncTask
And you can use callbacks to inform the activity that the task has finished
check https://stackoverflow.com/a/13947857/1434631
Yes, you can use AsyncTask
AsyncTask has a method called onPostExecute() which lets you know when your background process, in this case, loading data from server, is completed.
Here is a nice tutorial !

Android Asynk Task

is a good practice to have an Asynk task with a loop like this inside?
while (true) {
check queue and request API
Because i need to wait for my Activities and service needs to comunicate with the APi.
Thanks
I am assuming the "queue" is a Java queue, perhaps a LinkedBlockingQueue. If so, that queue is unnecessary, as AsyncTask has a queue to go along with its thread pool.
So, the question is: what triggers things to go in the queue?
If the trigger is a user event (e.g., menu choice, button push), just have it launch an AsyncTask, or have it have a Service launch an AsyncTask. That work will be queued up by the AsyncTask system.
If the trigger is the passage of time (e.g., we want to check an external server every 10 minutes), I would use AlarmManager and consider switching from AsyncTask and a Service to using an IntentService.
I have a priority queue in order to select first the important calls to the API.
My program have two services:
One calls the API when a message is added to the queue. The call to the api is made by an Asinc Task in this way:
messages.add(request);
new DownloadApiTask().execute();
The other service is updating the local database. For that, i have a loop in which i call the first service in order to get data from the API. The basic structure is:
while ihave data to updload
mFirstService.putMessage(request).
Fine, the problem is i have a rejected Execution Exception every X calls, I think it can be because i invoke the asinc task every time i take a message.
For that, i was thinking in force to the asinck task to check the queue instead executing it.
I hope you can understand my problem.
Thanks

Categories

Resources