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

在android中下载后,下载的文件丢失,android,Android,我正在使用以下代码将文件从服务器下载并保存到外部存储器,它在某些设备中运行良好,文件在外部存储器中可用,而在某些设备中,文件在下载后丢失。如何解决这个问题?此代码用于选项卡3(型号:SM-T311 OS:4.4.2),而不用于注释2(型号:GT-N7100 OS:4.4.2) 公共类下载AttachementSyncTask扩展 异步任务{ 私有字符串文件名; 私人对话; 私有字符串下载URL; 私有上下文ctx; 私有字符串attachmentName; 公共下载AttachementSync

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

公共类下载AttachementSyncTask扩展
异步任务{
私有字符串文件名;
私人对话;
私有字符串下载URL;
私有上下文ctx;
私有字符串attachmentName;
公共下载AttachementSyncTask(字符串文件名、上下文){
this.fileName=文件名;
this.attachmentName=文件名;
this.ctx=上下文;
}
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
dialog=新进度对话框(ctx);
setMessage(ctx.getString(R.string.download_attachements));
对话框。setCanceledOnTouchOutside(false);
dialog.show();
下载URL=文件名;
String[]parts=downloadUrl.split(“attachmentName=”);
字符串part1=parts[0];//004
fileName=parts[1];//034556
文件f=新文件(Environment.getExternalStorageDirectory()
.getAbsolutePath()+“/附件”);
如果(!f.exists())
f、 mkdirs();
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
试一试{
整数计数;
URL=新URL(下载URL);
URLConnection conexion=url.openConnection();
conexion.connect();
int lenghtOfFile=conexion.getContentLength();
InputStream输入=新的BufferedInputStream(url.openStream());
OutputStream输出=新文件OutputStream(环境
.getExternalStorageDirectory().getAbsolutePath()
+“/Attachments/”+文件名);
字节数据[]=新字节[1024];
长总计=0;
而((计数=输入。读取(数据))!=-1){
总数+=计数;
出版进度(“+(int)((总计*100)/长度文档));
输出.写入(数据,0,计数);
}
output.flush();
output.close();
input.close();
}捕获(例外e){
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串结果){
super.onPostExecute(结果);
if(dialog.isShowing()){
dialog.dismise();
字符串filename=Environment.getExternalStorageDirectory()
.getAbsolutePath()+“/Attachments/”+文件名;
文件=新文件(文件名);
意向意向=新意向(意向.行动\视图);
intent.setDataAndType(Uri.fromFile(file),“application/*”;
intent.setFlags(intent.FLAG\u活动\u否\u历史记录);
星触觉(意向);
}
}
}

您可能希望通过将日志级别更改为警告来检查异常。
如果(!f.exists())f.mkdirs();Log.e(标记,“创建的文件URI:+URI.fromFile(f.toString())你不能在那里大声说你创造了什么。您应该检查mkdirs的返回值,如果返回值为false,则不要继续。在onPostExecute中只使用Log。但用户看不到这一点。还可以使用Toast()通知用户。如果文件不存在,则不必启动该意图。
Environment.getExternalStorageDirectory().getAbsolutePath()+“/Attachments/”
。在一个异步任务中有三次。这是糟糕的编码实践。最好只执行一次。只有在有捕获时才返回null。否则返回“ok”。检查onPostExecute的结果参数是否为“ok”。最好不要在catch中返回null,而是“Exception:+e.getMessage();”;。通过这种方式,您可以在OnPostExecute中为用户Toast它。也记录异常。做一些正常的调试。
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);              
        }
    }
}