Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Download Zip to SD card?

Tags:

android

zip

I have a 100 meg zip file that I need to download when the app first starts. It needs to unzip to the SD card (400 meg).

I'd rather not have to have it touch the phone's storage as many phones won't have 400 meg free on the phone's storage.

Can this be done (any one have an example?)

Thanks, ian

like image 881
Ian Vink Avatar asked Jan 22 '23 16:01

Ian Vink


1 Answers

Can be done. What exactly are you looking for? The download routine or how to do the check? Here's the download method, you should run it in an AsyncTask or so.

/**
 * Downloads a remote file and stores it locally
 * @param from Remote URL of the file to download
 * @param to Local path where to store the file
 * @throws Exception Read/write exception
 */
static private void downloadFile(String from, String to) throws Exception {
    HttpURLConnection conn = (HttpURLConnection)new URL(from).openConnection();
    conn.setDoInput(true);
    conn.setConnectTimeout(10000); // timeout 10 secs
    conn.connect();
    InputStream input = conn.getInputStream();
    FileOutputStream fOut = new FileOutputStream(to);
    int byteCount = 0;
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = input.read(buffer)) != -1) {
        fOut.write(buffer, 0, bytesRead);
        byteCount += bytesRead;
    }
    fOut.flush();
    fOut.close();
}

You also might want to check whether the phone is at least connected to WiFi (and 3G);

// check for wifi or 3g
ConnectivityManager mgrConn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
TelephonyManager mgrTel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if ((mgrConn.getActiveNetworkInfo()!=null && mgrConn.getActiveNetworkInfo().getState()==NetworkInfo.State.CONNECTED)
       || mgrTel.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS) { 
 ...

otherwise people will get mad when they need to download 100m via a slow phone network.

like image 157
Mathias Conradt Avatar answered Jan 31 '23 21:01

Mathias Conradt