priyanka
priyanka

Reputation: 181

Download a file from server to phone

I am unable to download a file to a specified path on an Android phone from the server, but nothing happens when running this code.
I have used all the required permissions in the manifest file:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

This is my MainActivity class:

private final String PATH = "/storage/sdcard0/BT/";


public void DownloadFromUrl(String fileName1) {  //this is the downloader method
    try {

        URL url = new URL(f);

        File file = new File(fileName1);


        HttpURLConnection ucon = (HttpURLConnection) url.openConnection();

        ucon.setRequestMethod("GET");
        ucon.setDoOutput(true);
        ucon.connect();
        FileOutputStream fos = new FileOutputStream(file);

        InputStream is = ucon.getInputStream();

        BufferedInputStream bis = new BufferedInputStream(is);


        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

                    /* Convert the Bytes read to a String. */
       // FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();
       // Log.d("ImageManager", "download ready in"
         //       + ((System.currentTimeMillis() - startTime) / 1000)
           //     + " sec");

    } catch (IOException e) {
        Log.d("ImageManager", "Error: " + e);
    }

    }

Upvotes: 1

Views: 2576

Answers (1)

Mor Paz
Mor Paz

Reputation: 2223

In Android, you can't have network related tasks run on the main thread, the guidelines specify that the main thread is meant for UI tasks.

In order to perform network actions, such as downloading files, performing GET and POST requests and other various requests, you need to use AsyncTask

There are many ways to implement AsyncTask, and you can find many examples on Stack Overflow and also in other sites, I'll link a few below:

Please refer to the guides I supplied to get an idea on how to use AsyncTask to perform long running tasks in the app's background.

It shouldn't be too hard to use after you figure out the basic concept

Upvotes: 1

Related Questions