Hi i am working on an android application. Its a you tube type of application.
I am facing one issue . There is a download feature in my app. When i start downloading some content then during downloading if i will create any another network connection then it will take more time.
For Downloading i used a Asyntask handled by a services.
and for simple network call i used a Asyntask.
Then kindly please suggest me how can i overcome with this problem.
My expectation is if downloading is in progress then if i make some network call then this network call should be on high priority.
Please suggest.
If you are using asynctask, you can attempt setting the priority of the current thread using something like this.
protected void doInBackground() {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
// download the things
}
Asynctasks are usually lower priority. You can read more about it here:
http://www.androiddesignpatterns.com/2014/01/thread-scheduling-in-android.html
If you are using many HTTP requests, I do however recommend you use a library, like Volley. This allows you to easily set up a request queue, and jump the queue for high priority items.
You can read more about that, here:
http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/
Related
I am a Java developer with no Android experience, and I am trying to quickly put an app together. It seems that what I would normally do in Java isn't helping.
At this stage, ease of implementation is more important than efficiency or style - I will sort the latter out when there is more time and I will have educated myself properly when it comes to Android.
People can use the app to ask for support, or offer it to those who need it. Asking for support posts a request with the details to the server, and that's done.
Now I would like the app to post an asynchronous request to the server, to be notified of outstanding support requests once a minute. I guess it's the same principle of WhatsApp checking if there is any new message on the server.
I tried doing that in a separate thread with an infinite loop which sleeps for 60 seconds but for some reasons that stops the UI from working.
From what I now understand, I should use a service with a Looper, a Timer and a Handler. Is that correct?
Could anybody point me to a tutorial which explains exactly what to do, step by step? Or at least suggest keywords I should look for?
All I found so far are snippets of code which don't work together when I try to assemble it. Possibly because I am not searching for the right terms?
Thanks, Dan
You could try the following approach:
Create a service that runs in the background to check for newly added data in the server.
If you prefer to make it user-driven, you can let users refresh the list on the device to actually trigger the requests to the server.
Libraries like Retrofit can make your life easier when it comes to making http requests - always avoid the main UI thread when doing this.
Another library that you could use to decouple your application using Events is EventBus. Assuming you are running a background service to check for updates, you can use EventBus to update your User Interfaces when something new is retrieved from the server through a GET request.
I hope this gives you an idea on how to proceed with the solution. Good luck!
I'm trying to make a web app using the WebView component. I need to modify the HTML before I show it to the user, so I tried to download it, modify it and the load it. I did this using the HTTP response and get classes and because of a series of exception I had to put them in an AsyncTask. Now the problem is that this solution works but it has a short delay because I have to wait for the Thread to end and then I can call the WebView.load() method either for the home and the other links. It is really ugly...do you have any solution to suggest me? Something without Async Tasks maybe?
The Android documentation states, that you should NEVER perform network operations on the main thread (otherwise, it will give you an exception).
Waiting for the AsyncTask to complete its background workflow is a natural process similar to think over the problem before giving the solution (your brain need to compute it in the background, if you will).
You will wait in any case. The server can't provide information instantly. But if you make request not in AsyncTask, it will block your application. And then android will offer to stop it. You dont need it. Instead of this you need to show something like process dialog.
I am new to Android Development. Sorry for a dumb question.
I need to check several http resources (resource1, resource2... etc) and check if they are up. If resource 1 is unavailable, then the app needs to check if internet is up (probably ping google?) and then if the connection is actually working it needs to check all the other resources and place the information about what is down to the notification drawer.
It's pretty straightforward to do it with AsyncTask and HttpURLConnection for one resource but i don't quite understand how to follow execution logic with async calls (resource1 -> google -> resource2 -> gather info in one place -> display notification). What is the best practice for it?
#FD_'s answer is valid but I think there is a better way that avoids the horrors of the Async Task. For the record I upvoted FD_'s answer as it is valid I am just pointing out another way.
So I would make a result object. This can be used to work out what happened when you tried to communicate with the various services. You could have something like
public class ResponseResult {
public String displayName; // so we know what this was all about e.g. "google request"
public boolean success;
public String message;
public int httpStatusCode; //useful to help workout what went wrong e.g. 500, 302 etc.
}
You could then use something like the Android Volley Library that is better than an AsyncTask as it uses a RequestQueue in another thread, which survives the Activity lifecycle better. It also might make your code a little easier to read/manage.
You can read a little about Volley Vs AsyncTask here - Volley and AsyncTask
Once you have issues all your requests and put the results in an Array or List, you could then iterate over them to print the result.
You can get Volley from here https://android.googlesource.com/platform/frameworks/volley
Additional Info
You might also find this inforgraphic from Robospice to be useful as it helps to explain the drawbacks of an AsyncTask.
https://raw.github.com/octo-online/robospice/master/gfx/RoboSpice-InfoGraphics.png
Another implementation
You may find this implementation is not suitable but it makes some sense and would produce even less code.
You could write some server side code to do the checks for you and return an XML/JSON array of result objects. This has the advantage of a single request to a hardwired server with a more reliable connection, that possibly could make the requests in a shorter space of time.
Your Android device would only issue a single request to the server and then process the result array per my other method above.
The major drawback is that this would introduce another set of code and additional hardware.
I would encourage using Volley library for that purpose also. Check past Google IO 2013 interesting video about it.
Advantages of using Volley:
Volley automatically schedule all network requests. It means that
Volley will be taking care of all the network requests your app
executes for fetching response or image from web.
Volley provides transparent disk and memory caching.
Volley provides powerful cancellation request API. It means that you
can cancel a single request or you can set blocks or scopes of
requests to cancel.
Volley provides powerful customization abilities.
Volley provides Debugging and tracing tools
VIDEO: Google I/O 2013 – Volley: Easy, Fast Networking for Android
**source*: http://www.technotalkative.com/android-volley-library-example/
On the other hand, once one of those resources is unavailable, you don't have to ping google as you said. Android API has facilities to check whether your mobile is connected to the Internet; something like this would be enough:
private boolean isConnectedToInternet() {
return (((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null);
}
Just perform all your logic and internet operations in one place, in the same AsyncTask. Create a class that holds all result information and implement your AsyncTask to return (eg send to a delegate/listener/call main thread method) an instance of that class.
If you like to execute your async task using similar syntax as Jquery's $ajax, this article shows you how to do it. With very little code in the article and Java 8's lambda expression, you will be able to write your async code like this:
Async.run(() -> {
//code will be executed on a background thread
MyAPI api = new MyAPI()
return api.loadData();
})
.whenComplete((data) -> {
//back on UI thread, update UI using data returned
})
.onError((ex) -> {
//handle exception on UI thread
})
.execute();
How do I download multiple files in a queue one by one! I'm using this as a sample code, since.
I would be passing the URLs to download in Strings from my local DB dynamically.
Please let me know how to do that. I want the download to start as soon as the application launches. Kindly help me out!
Android Dev Type: Newbie
Purpose of Download Queue: To download multiple files from the server after in-app billing gets successful!
P.S.: I already referenced this question. But I'm not sure if that would solve my issue!
A good way of queuing up requests to be handled asynchronously, one at a time, is with an IntentService. If you have an IntentService which reads URLs from the supplied Intent, then all you have to do is create an Intent for each file you want to download, and send each Intent to the service,
Here is a good tutorial.
EDIT: I see you've already referred to a similar question, where the answer recommends IntentService. So, maybe you should use an IntentService. :)
From API 11 up, a good approach is to use a FixedThreadPool with async tasks. Do once:
ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(3);
Where 3 is the number of downloads you want to run at the same time. It will queueu the task if there are already 3 downloads running, and automatically handle the task later.
Launch your async tasks with:
yourAsynTask.executeOnExecutor(threadPoolExecutor, params);
Params is probably the url you wish to connect to. You can read it out in the onPostExecute of your asynctask, and connect to the server using a HttpURLConnection.
Make sure you call down this on shutdown:
threadPoolExecutor.shutdown()
What's the best way to implement a download queue in Android?
Use an IntentService. It supplies the queue and the background thread for you, so all you have to do is put your download logic in onHandleIntent(). See here for a sample project demonstrating this.
I'm building this client for a web service.
Pretty much everything makes requests to a server and now what I do is, I open a new thread and put all my requests in the same thread. That means I'm making all my requests in a serial way inside the thread and that turns into a lot of waiting for the user. Aiming to make the application faster, I want to make every server request in an asynchronous way.
I have a Networking class that handles all the HTTP requests I need and I'm thinking of making it so that every request starts its own thread.
I'm thinking of using ASyncTask for this but I noticed that with ASyncTask I'd need a class for each of my http requests (a class for GET, POST, PUT, etc). Is that the best way of doing it? is there a more efficient/clean way of doing this? What do you guys suggest.
Seems like a design decision that will depend on exactly what you are up to. There are various ways in Android to execute tasks depending on whether the user is waiting for some data or is being notified later on once the background task completes.
I would suggest you to look at this post that compares various task mechanisms in Android. Apart from this also go through the java.util.concurrent package.
I'm sorry this is not a concrete answer, but take it from me - it mostly depends on how are you trying to serve the user. So one can only suggest ideas. Hope this helps.