サーバーからファイルをダウンロードするアプリがあります。ダウンロードは Asynctask にあります。ダウンロードの進行状況を示す進行状況バーがあります。ファイルのダウンロードが完了するまでに時間がかかりすぎる場合は、キャンセル リクエストを送信します。これは進行状況ダイアログを閉じるだけで、ファイルを再度クリックしてもダウンロードは再開されません。このシナリオをどのように処理しますか。多くの調査により、私は多くの混乱を残しました...ダウンロード時にダウンロードの進行状況を表示するのと同じくらい簡単だと思いました-> OnCancel、ダウンロードを強制終了します(残念ながら、Asynctaskを強制終了する方法が見つかりません)->ファイル、ダウンロードを再開します.....しかし、残念ながら、私は方法を取得していないようです...助けてください...
これが私がやっていることの源です...
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// showDialog(DIALOG_DOWNLOAD_PROGRESS);//to test i commented
mProgressDialog = new ProgressDialog(Shelf_books.this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
/*mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
mytask.cancel(true);
}
});*/
mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
mytask.cancel(true);
}
});
mProgressDialog.show();
}
protected void onProgressUpdate(String... progress) {
Log.d("kunal",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected void onCancelled() {
Log.d("kunal","cancel method");
running = false;
}
@Override
protected String doInBackground(String... arg1) {
// TODO Auto-generated method stub
int count;
if(isCancelled()==false)//test
{//test
try{
URL url = new URL(arg1[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("kunal", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(file);
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.d("kunal","exception occured");
}
}//test
return null;
}
}
/*creating async class ends here*/
}
以下は onExecute の呼び出しです。これはボタンのクリックで呼び出されます...
public void DownloadFile(String fileURL, File directory) {
/*testing my code here starts */
try {
URL u = new URL(fileURL);
new DownloadFileAsync().execute(fileURL);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}