为什么不删除asynctask中的不完整文件

时间:2014-03-03 07:06:56

标签: android android-asynctask

我在asynctask中使用onCancelled()来删除不完整的文件但是当下载不完整的文件时不要删除它。 (文件是音乐)

为什么不删除以下代码中的不完整文件?

我的api是8

这是我的代码:

public class ZiaratMatn4 extends Activity implements OnClickListener {
 MediaPlayer mp;
 ImageButton btndownziarat;
 ImageButton btnplayziarat;
 SeekBar seek_bar;
 Handler seekHandler = new Handler();
  private ProgressDialog pDialog;
  public static final int progress_bar_type = 0;
  private static String file_url = "http://upir.ir/files92be/2eda2a6a5434.mp3";
  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ziaratmatn);
    mp = MediaPlayer.create(this,Uri.fromFile(audioFile));
    btnplayziarat = (ImageButton) findViewById(R.id.btnplayziarat);
    btnplayziarat.setOnClickListener(this);
    btndownziarat = (ImageButton) findViewById(R.id.btndownziarat);
    btndownziarat.setOnClickListener(this);     
    getInit();
 seekUpdation();
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
File sdcard = Environment.getExternalStorageDirectory();
File audioFile = new File(sdcard.getPath() + "/EBKH/basem-vares.mp3");
 public void getInit() {
     if(audioFile.exists())
        {
     seek_bar = (SeekBar) findViewById(R.id.sbziarat);
 seek_bar.setMax(mp.getDuration());
 }}
@Override
public void onClick(View v) {
    switch(v.getId())
    {
    case R.id.btnplayziarat :
        if(audioFile.exists())
        {
                if(mp!=null)
                {
                   if(mp.isPlaying())
                   {
                      mp.pause();
                      btnplayziarat.setImageResource(R.drawable.play);
                   }   
                   else
                   {
                     mp.start();
                     btnplayziarat.setImageResource(R.drawable.puse);
                   }}}
        break;
    case R.id.btndownziarat :
        if(!new File(Environment.getExternalStorageDirectory().toString() + "/EBKH/basem-vares.mp3").exists())          
             new DownloadFileFromURL().execute(file_url);
       break;   
 }}
 Runnable run = new Runnable() {
        @Override
        public void run() {
            seekUpdation();
        }
    };
    public void seekUpdation() {
        if(audioFile.exists())
        {
        seek_bar.setProgress(mp.getCurrentPosition());
        seekHandler.postDelayed(run, 1000);
    }}
 @Override
 protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
    pDialog = new ProgressDialog(this);
    pDialog.setMessage("در حال دانلود،لطفا صبور باشید...");
    pDialog.setIndeterminate(false);
    pDialog.setMax(100);
    pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    pDialog.setCancelable(true);
    pDialog.show();
    return pDialog;
default:
    return null;
}
 }

 class DownloadFileFromURL extends AsyncTask<String, String, String> {
@Override
protected void onCancelled() {
    File file= new File("/sdcard/EBKH/basem-vares.mp3");
    file.delete();
}
@Override
protected void onPreExecute() {
    super.onPreExecute();
    showDialog(progress_bar_type);
}
@Override
protected String doInBackground(String... f_url) {
    int count;
try {
    URL url = new URL(f_url[0]);
    URLConnection conection = url.openConnection();
    conection.connect();
    int lenghtOfFile = conection.getContentLength();
    InputStream input = new BufferedInputStream(url.openStream(), 8192);
    OutputStream output = new FileOutputStream("/sdcard/EBKH/basem-vares.mp3");
    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) {
    Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String file_url) {
    dismissDialog(progress_bar_type);
}}}

2 个答案:

答案 0 :(得分:0)

我不确定这里发生了什么,但可能有帮助的是在末尾添加finally{}块,检查读取的总字节数是否等于文件。如果没有,请删除该文件。

答案 1 :(得分:0)

这是因为你永远不会取消AsyncTask!您需要在AsyncTask对象上调用cancel(),但要做到这一点,您需要先将实例保存在变量中。

首先,保留AsyncTask的实例,因此在类中声明任务

DownloadFileFromURL downloadTask;

创建任务时,将其分配给变量

downloadTask = new DownloadFileFromURL().execute(file_url);

无论何时您想取消,请致电:

downloadTask.cancel();