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.
Related
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.
I have a two part question. Both are somewhat general.
I'm creating an app that relies heavily on communication with a server. I plan to have different classes for each repository I'll need. Is an Android service the correct pattern to use here? There may be certain situations where I'll want to cache things between activities. Will a service allow me to do this?
Assuming a service is what I want to use for this, how can I load content once the service is bound. When the user opens the app, I want to start loading content. However, binding a service isn't blocking, so I can't write the code that makes requests with the service in my onStart() right? Is there some helper class that will wait for the service to load then execute a function? I know I could put some code in my onServiceConnected() method but I'd like to stay away from coupling like that.
Hopefully that wasn't too abstract. Thanks in advance.
Yes, Service is the way to go, but a started service, not a bound one.
You could make async request methods, and the Service can broadcast the result back to your Activity.
The async request in this case is a startService(intent) with an
Intent containing the request parameters. The service would start a background thread for the operation, optimally you can use a networking library for this (for example Volley).
And the reply is a broadcast by the Service with the relevant data.
This answers the problem of caching, because the Service can decide what to return. So in case the Service does not have the requested resource, it will download (and return) it. But if the Service has the resource, then it will just simply return the cached version.
To start, you should get yourself familiar with these topics:
Started Services (for the requests)
LocalBroadcastReceiver (for the reply)
Event Bus (alternative to LocalBroadcastReceiver, for example Otto)
I don't know much about your concrete needs, but it seems like you want to implement a REST client with cache. There is a really good Google IO presentation on that here. Definately worth to watch!
1)If you need code to run even when your Activity isn't, the correct answer is a Service. If you just need to cache data, then storing it in a global static variable somewhere may be ok.
2)Your service can start a Thread or AsyncTask. These execute in parallel. onStartCommand generally launches it in this case.
As with most things, the answer to these questions are subjective at best. I would need more information then I currently have, but I'll take a vague, general stab at this...
If you need something persistently hitting your server repeatedly I would say use a service.
Where you call it is not nearly as important as how many times it needs to be called. That being said the answer is yes. If you need this data as soon as the application or activity loads, then the onCreate method is where it needs to be loaded.
My reccomendation is either A) service or B)AsyncTask.
Go with A if you have to hit the server repeatedly for data and need it in regular intervals. Otherwise go with an AsyncTask and load all the data you need into an object for storage. Then you can use it as you need and it will essentially be "cached".
The difference between the two is simply "best tool for the job". I see you use some javascript. To give a proper analogy, using a service for a server call rather than an async task, is the equivalent of using a web socket (node js) when you could of just used an ajax call. Hope this helps. Oh and PS, please don't use static variables in 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.
I am posting images using JSON. Whenever I take a picture i have to call the webservice.
This webservice call may take some time. I dont want to use Thread nor Asynchronous Task for this.
I want to call the Webservice in background and able to perform operations in foreground(button click, entering some data in edittext etc).
I guess this can be achieved by using Service. Please provide me some tutorials for this.
Is there any way?
Thanks in advance.
Services are basically used when we want to run some code in background even when a application or the present activity gets closed. Use Services only if you need it and be sure to destroy it when you are done otherwise you will waste memory and that is not good.
Here are some great tutorials of implementing service. Firstly make some sample codes to learn how to handle services and see their lifecycle, etc. and then try to implement them in you code otherwise you may be confused xamarin.com vogella.com and technotopia.com. Happy Coding!!!
If you need to handle upload within a serial queue service, take a look at IntentService.
and implement the abstracted onHandleIntent() method.
I have my MainActivity which gives the user a selection of pages to open, all of which involve downloading some data from the internet and displaying it. To save the user waiting when they choose their page I've made an AsyncTask as a subclass of MainActivity which produces an object DATAwhen the download is complete.
How would I pass DATA on to the SecondActivity in the following circumstances:
The user chooses the SecondActivity before the AsyncTask download has completed.
The download completes before the user chooses the SecondActivity.
the AsyncTask doesn't have to be a sub-class of MainActivity its just been tidy to do it that way so far,
thanks for the help!
Here's one way to do this:
Create a reference to your data in your Application. The Android Application is a good place to store global data. Next, populate the data via your AsyncTask (Watch out for the pitfalls of using an AsyncTask). You can now access your data via a call similar to this: ((MyApplication)getApplication).mydata
As you mentioned, two scenarios can come up. Either the data has been populated, or not. To handle this, use an observer that observes changes to the data. Have SecondActivity register as an observer when the data is null. When the data is available your SecondActivity's update method will get called and you can do whatever you please with it. Finally, make sure to unregister from being an observer.
Hope this helps.
Passing information directly between activities works only if it is Parcellable (via Intent). Almost anything could be made Parcellable but it is not always a good idea especially when the amount of data is large.
The next problem is that your AsyncTask most likely keeps the Context of your first activity alive when it is running longer than the activity lasts. Activity instances are quite often recreated when you rotate the device and naive implementations tend to start another asynctask in the new instance and end up with multiple tasks that download the same data. You would need to pass the reference of a running task between instances of the same Activity.
The simplest solution is probably to create a singleton (or a Service) accessible from both activities that hosts the AsyncTask & loads the data. If it requires a Context use getApplicationContext() since that's safe to use outside the lifetime of Activites.
Activities could register themselves as listeners for "data loaded" events while they are active.
I've recently struggled with AsyncTask and had difficulty having the UI behave while the task was running in the background. While there are comments around that services aren't really appropriate for the sort of thing you're describing, I've found them much easier to work with. You might check intentService as a middle ground. Good tut's can be found here and, specifically concerning intentService, here.