2014-03-03 5 views
-1

불완전한 파일을 지우려면 asynctask에서 onCancelled()를 사용하지만 다운로드하지 않으면 불완전한 파일을 삭제할 수 없습니다. (파일은 음악 임)asynctask에서 불완전한 파일을 지우지 않는 이유는 무엇입니까?

왜 다음 코드에서 불완전한 파일을 삭제하지 않으시겠습니까?

이 내 코드 8

내 API입니다 : 여기에 무슨 일뿐만 아니라 확실하지 오전

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); 
}}} 

답변

0

무엇 도움이 검사 끝에 finally{} 블록을 추가 읽은 총 바이트가 파일의 길이와 같은 경우 그렇지 않은 경우 파일을 삭제하십시오.

0

AsyncTask를 취소 한 적이 없기 때문입니다! AsyncTask 객체에서 cancel()으로 호출해야하지만, 그렇게하려면 먼저 변수를 인스턴스에 유지해야합니다. 그래서 일단

는 AsyncTask를 인스턴스를 유지하므로 수업 시간에 작업을 선언

DownloadFileFromURL downloadTask; 

태스크를 만들 때, 당신의 변수

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

에 할당 그리고 때마다 당신이 원하는 취소하려면 다음 번호로 전화하십시오.

downloadTask.cancel(); 
+0

농담해야합니다! – Merlevede

관련 문제