使用Android下载ZIP文件

时间:2012-10-23 08:26:55

标签: android download runtime-error

我正在尝试从服务器下载zip文件。为此,我使用以下代码:

        String path = Environment.getExternalStorageDirectory().toString() + "/KaLePro/";
        StartscreenModel sm = StartscreenModel.getInstance();
        //TODO FIX: unkown error! Bring usb-cable to find out!
        try {
            URL url = new URL(urlString);
            System.out.println("Connecting to " + url);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.connect();
            int fileLength = connection.getContentLength();

            File PATH = new File(path + "import/");
            if (!PATH.exists()) {
                PATH.mkdirs();
            }

            File outputFile = new File(PATH, "tmp.zip");

            InputStream input = connection.getInputStream();
            OutputStream output = new FileOutputStream(outputFile);

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            sm.setSubMax(100);
            while ((count = input.read(data)) != -1) {
                total += count;
                sm.setSubStep((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();
            Toast.makeText(Booklist.this, "Download fertig.", Toast.LENGTH_SHORT).show();
        } catch (MalformedURLException e) {
            Toast.makeText(Booklist.this, "Keine gültige URL", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Toast.makeText(Booklist.this, "Keine Verbindung zur URL", Toast.LENGTH_SHORT).show();
        }

但是当我尝试下载该文件时,我收到以下Logcat错误:

10-23 10:22:37.867: E/AndroidRuntime(21490): FATAL EXCEPTION: main
10-23 10:22:37.867: E/AndroidRuntime(21490): android.os.NetworkOnMainThreadException
10-23 10:22:37.867: E/AndroidRuntime(21490):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at libcore.io.IoBridge.connect(IoBridge.java:112)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at java.net.Socket.connect(Socket.java:842)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:76)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at de.isogon.kalepro.activities.Booklist$2.onDownload(Booklist.java:194)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at de.isogon.kalepro.views.dialogs.DialogDownload$2.onClick(DialogDownload.java:76)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at android.view.View.performClick(View.java:4211)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at android.view.View$PerformClick.run(View.java:17267)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at android.os.Handler.handleCallback(Handler.java:615)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at android.os.Handler.dispatchMessage(Handler.java:92)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at android.os.Looper.loop(Looper.java:137)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at android.app.ActivityThread.main(ActivityThread.java:4898)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at java.lang.reflect.Method.invokeNative(Native Method)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at java.lang.reflect.Method.invoke(Method.java:511)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
10-23 10:22:37.867: E/AndroidRuntime(21490):    at dalvik.system.NativeStart.main(Native Method)

其中de.isogon.kalepro.activities.Booklist $ 2.onDownload(Booklist.java:194)链接到connection.connect();上面的代码。

我的清单权限如下:

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

我已经尝试过很多下载代码示例 - 所有这些都似乎产生了几乎相同的错误。

4 个答案:

答案 0 :(得分:2)

正如您从Logcat中看到的那样:10-23 10:22:37.867: E/AndroidRuntime(21490): android.os.NetworkOnMainThreadException

这不起作用的原因是因为您正在使用UI线程。尝试将下载添加到在单独的线程上运行的AsyncTask ir。

答案 1 :(得分:1)

请不要在主UI线程中编写网络调用,使用另一个线程,它将解决您的问题,并在下面链接获取更多信息。

Why Ice Cream Sandwich Crashes Your App

答案 2 :(得分:0)

我使用此课程

public class ZipUtility {
    public static final void zipDirectory(File directory, File zip)
            throws IOException {
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip));
        zip(directory, directory, zos);
        zos.close();
    }

    private static final void zip(File directory, File base, ZipOutputStream zos)
            throws IOException {
        File[] files = directory.listFiles();
        byte[] buffer = new byte[8192];
        int read = 0;
        for (int i = 0, n = files.length; i < n; i++) {
            if (files[i].isDirectory()) {
                zip(files[i], base, zos);
            } else {
                FileInputStream in = new FileInputStream(files[i]);
                ZipEntry entry = new ZipEntry(files[i].getPath().substring(
                        base.getPath().length() + 1));
                zos.putNextEntry(entry);
                while (-1 != (read = in.read(buffer))) {
                    zos.write(buffer, 0, read);
                }
                in.close();
            }
        }
    }

    public static final void unzip(File zip, File extractTo) throws IOException {
        ZipFile archive = new ZipFile(zip);
        Enumeration e = archive.entries();
        while (e.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            File file = new File(extractTo, entry.getName());
            if (entry.isDirectory() && !file.exists()) {
                file.mkdirs();
            } else {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }

                InputStream in = archive.getInputStream(entry);
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(file));

                byte[] buffer = new byte[8192];
                int read;

                while (-1 != (read = in.read(buffer))) {
                    out.write(buffer, 0, read);
                }

                in.close();
                out.close();
            }
        }
    }
}

答案 3 :(得分:0)

NetworkOnMainThreadException是因为您尝试在主线程上执行网络操作。您应该创建一个AsyncTask并下载该文件

应该相当容易,你的大部分代码都可以放在asyncTask中的doInBackground中