安卓系统-从互联网下载文件到SD卡-最安全的方法



我正在开发一个应用程序,需要从互联网下载文件并将其存储在SDCard上。我注意到有些设备在下载时会报告错误,例如"解析错误"。我假设有些设备没有SDCard,或者我在课堂上得到的路径不正确。如果没有SD卡或未安装SD卡,支持所有设备的最安全方法是什么?这是我的代码:

/**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();
                // getting file length
                int lenghtOfFile = conection.getContentLength();
                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(), 8192);
                // Output stream to write file
                OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/Download/file.apk");
                byte data[] = new byte[1024];
                long total = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress(""+(int)((total*100)/lenghtOfFile));
                    // writing data to file
                    output.write(data, 0, count);
                }
                // flushing output
                output.flush();
                // closing streams
                output.close();
                input.close();
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }
            return null;
        }

我认为问题可能出在这条线上:

OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/Download/file.apk");

我应该使用getExternalStorageDirectory()并下载吗?或者是否存在所有设备通用的"最安全"位置?

首先,您不想使用AsyncTask下载文件。因为如果用户杀死了承载Task的屏幕,下载也会被杀死。调查IntentService。

其次,熟悉这里的Android代码示例:http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

您可以检查可用的目录,然后获取相应的目录。

最新更新