I'm making a login post request from android phone.
Returned result will be 'success' or 'fail'.
I can make this post request using either a IntentService or an Activity, both will work fine.
Case I'm concerned about:
Phone rings (activity paused/destroyed) before receiving the result from the web service.
Will I miss the result in this case?
I want the result of web service to be saved even if the activity stops before accepting the result.
Is there anyway it'll work using Activity or do I need to receive the result using an IntentService ?
It should be on the service, the best way of finding bad behavior like this is to enable strict mode on your application.
If you put it on the activity it will block the activity.
Any request sent from the Activity results in NetworkOnMainThreadException being raised - you must not call any http request from UI thread (How to fix android.os.NetworkOnMainThreadException?)
Delegating the request to IntentService and notifying Activity via Broadcast (opitionally prioritized Broadcast to handle cases when your Activity is in background while the Broadcast is delivered to the receiver) is the easiest approach I think.
Alternatively, you can use AsyncTask but you must handle screen rotation and remember about task cancellation.
You can extend AsyncTaskLoader and provide your custom loader but you still must remember about request cancellation (http://www.androiddesignpatterns.com/2012/08/implementing-loaders.html).
An third-party open source, maybe? OkHttp allows you to execute asynchronous Http requests. In addition there is a cancel() method on a Call object which executes the request. Thus, you can easily use it in the activity
https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/com/squareup/okhttp/recipes/AsynchronousGet.java
Indeed, the StrictMode is a good tool that validates errors during development.
Related
I'm about to write an application that sends data to a server with a post request. These requests can fail and if they do I want them to be sent when the connection is back online.
What is the best way to implement this behavior?
EDIT
I've read some articles and come up with the following idea. I register a BroadcastReceiver in the manifest and tell it to listen for android.net.conn.CONNECTIVITY_CHANGE and android.net.wifi.WIFI_STATE_CHANGED. When the request can't be send I store the request. If the connection becomes alive then I will send the cached requests.
What is the best way to implement this behavior?
Make Volley requests from a bound Service, and send the result back to the Activity if it is still in the foreground.
EDIT:
won't this be a problem if the user decides to close the application?
That's exactly why you need to use a Service. If you do it from an Activity, the request continues even when the Activity is dismissed. If your Volley request is expressed as an anonymous class instance, it continues to hold an implicit reference to the outer Activity class, which leads to a memory leak / exception.
Check your Internet Connection continuously by using Handler or service ,if it is sends the data to the server otherwise dont send it.
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 =).
I have finished to write webservice in android. But if there is no service or connection or network problem, webservice is searching for that. It takes time. How will handle webservice calling in slow response from webservice?
Can any one assist me to handle this issue?
You need to call the webservice from either a service (docs here) or an AsyncTask (docs here). If you're going to be interacting with the webservice for a while, then I would use the former. Otherwise, I would use an AsyncTask. The main thing to remember is make sure that you do NOT make this call on the main thread or your application will most likely block and Android will display an ANR dialog.
Also, note that, if you use a service, you need to start a new thread and launch the service from that thread to help prevent the application from blocking.
There's a tutorial here that might be helpful.
Hope this helps!
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.
I'm developing restful android application, but I'm still newbie to android, and I would like to avoid beginners bed structural design that would cost me troubles latter.
I've read lots of discussions about android services and restful applications, many of them contrary to each other, so I would like to know have I choosen a good approach.
Inspired by this presentation http://www.youtube.com/watch?v=xHXn3Kg2IQE I put my http requests into IntentServices, instead of the Async Task.
I've choose Intent Service because of:
as a services they are not sensitive to foreground/background switching like Activities (won't get killed).
Intent service provides work in separate thread, so the user interface stays responsive.
Since Intent Service cannot run multiple request simultaneously, I've "split" my domain into few groups and for each group I have written my Intent Service. (ends up in: one CRUD set -> one intent service)
This way I got that inside of a group can be only one request running at a time (And this is good for me, since this way it could never be executed for example update and delete at same unit).
And, on the other side, I can run multiple requests at the same time if they are from the other groups, and don't affect each other.
So basically, I have this:
one generic HTTPRequest class that builds requests from name value pairs
UserIntentService - creates user related requests and executes it by using HTTPRequest cass, and proccess request using UserProcessor. Notifies caller by intent with data.
CallIntentService - creates call related requests and executes it by using HTTPRequest cass
and proccess request using CallProcessor. Notifies caller by intent with data.
UserProcessor - parsing response
CallProcessor - parsing response
ServiceHelper - finds and starts right intent service
When using from activity, I use something like this: SeviceHelper.StartService (action, data),
and I get response by local BroadcastReceiver inside of the activity. I register receiver on the OnStart(), and unregister it on the onStop() method of the activity.
Is that a good approach?
Should I have only one IntentService for all calls?
Is it better to have one Service that runs all the time in background, instead of using Intent Service that has to be started for each request?
Is there any other things that can get bad with this approach that I'm missing?