将Android下载的Zip文件保存到SD卡上?

4

我有一个100兆的压缩文件需要在应用程序首次启动时下载。它需要解压到SD卡(400兆)。

我不想让它接触手机存储,因为许多手机的存储空间可能没有400兆的自由空间。

这能做到吗(有人有示例吗?)

谢谢, Ian

1个回答

9

可以完成。你具体想要什么?下载程序还是如何进行检查? 这是下载方法,应该在AsyncTask或其他任务执行器中运行。

/**
 * 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();
}

您可能还想检查手机是否至少连接到WiFi(和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) { 
 ...

否则,当人们需要通过慢速手机网络下载100兆字节的内容时,他们会感到非常生气。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接