Xyz3R
Xyz3R

Reputation: 1074

Download file without asyncTask

I wanted to know if there is a way to download a file to an android devices without using an async task.

My problem is that I want to use an async task in my app, and i need to call a download function INSIDE this asyncTask, but android's documentation says that it is only possible to create an asyncTask from the UI thread.

I tried creating a thread by using extends thread instead of extends asyncTask, but android still gave the "Network on UI thread exception".

I need a function that works like this: String downloadFile(String url){...} that returns the downloaded String (i'm downloading an xml file, nothing fancy)

Upvotes: 1

Views: 1147

Answers (2)

CommonsWare
CommonsWare

Reputation: 1006819

and i need to call a download function INSIDE this asyncTask

If "INSIDE this asyncTask" really means "from the doInBackground() method of the AsyncTask", then the "download function" (whatever that is) does not need to be asynchronous.

but android still said the "Network on UI thread exception"

Then you are not doing the network I/O from doInBackground() of an AsyncTask or by any background means (e.g., from a regular Thread that you fork).

Upvotes: 2

Ramesh Sangili
Ramesh Sangili

Reputation: 1631

You can Services to download a file in Android.

A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. Each service class must have a corresponding declaration in its package's AndroidManifest.xml. Services can be started with Context.startService() and Context.bindService().

Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work. More information on this can be found in Processes and Threads. The IntentService class is available as a standard implementation of Service that has its own thread where it schedules its work to be done.

http://www.java2s.com/Code/Android/Network/FileDownloadService.htm

Upvotes: 0

Related Questions