在android下载后,下载的文件丢失了

时间:2015-06-17 07:41:08

标签: android

我正在使用以下代码将文件从服务器下载并保存到外部存储,它在某些设备上运行良好,文件在外部存储器中可用,而在某些设备中,文件在下载后丢失。如何解决这个问题?此代码适用于Tab 3(型号:SM-T311 OS:4.4.2),而不适用于注2(型号:GT-N7100 OS:4.4.2)

public class DownloadLoadAttachementAsyncTask extends
        AsyncTask<String, String, String> {
    private String fileName;
    private ProgressDialog dialog;
    private String downloadUrl;
    private Context ctx;
    private String attachmentName;

    public DownloadLoadAttachementAsyncTask(String fileName, Context context) {

        this.fileName = fileName;
        this.attachmentName = fileName;         
        this.ctx = context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(ctx);
        dialog.setMessage(ctx.getString(R.string.download_attachements));
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        downloadUrl = fileName;         
        String[] parts = downloadUrl.split("attachmentName=");
        String part1 = parts[0]; // 004
        fileName = parts[1]; // 034556
        File f = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/Attachments");
        if (!f.exists())
            f.mkdirs();

    }

    @Override
    protected String doInBackground(String... params) {
        try {
            int count;
            URL url = new URL(downloadUrl);
            URLConnection conexion = url.openConnection();
            conexion.connect();
            int lenghtOfFile = conexion.getContentLength();             

            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(Environment
                    .getExternalStorageDirectory().getAbsolutePath()
                    + "/Attachments/" + fileName);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
        }
        return null;

    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (dialog.isShowing()) {
            dialog.dismiss();
            String filename = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/Attachments/" + fileName;

            File file = new File(filename);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file), "application/*");
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            startActivity(intent);              
        }
    }
}

0 个答案:

没有答案