我正在开发一个应用程序,主要专注于从 Web 服务下载文件并将其存储在 sd 卡中。一切都很顺利,直到我的客户需要取消正在进行的下载。我尝试了很多方法,但我失败了。所以任何人都可以帮助我并发布一些片段以取消下载。意向服务将是首选。
编辑:
Toast.makeText(ThumbnailView.this, R.string.Download_start, Toast.LENGTH_SHORT).show();
pb.setVisibility(View.VISIBLE);
info_icon.setVisibility(View.INVISIBLE);
langBtn.setVisibility(View.INVISIBLE);
name.setVisibility(View.INVISIBLE );
author.setVisibility(View.INVISIBLE );
lastReading.setVisibility(View.INVISIBLE);
intent = new Intent(ThumbnailView.this,
DownloadAndExtractFiles.class);
Common.isDownloadProgress = true;
intent.putExtra("BEAN", bean);
intent.putExtra("FROM", "library");
intent.putExtra("receiverTag", mReceiver);
startService(intent);
意图服务类:
try {
File file = new File(path, /* BOOK_ID */filename + fileformat);
if (file.exists())
file.delete();
file.createNewFile();
output = new FileOutputStream(file);
finalpath = path + "/" + filename + fileformat;
Log.d("book UNEXTR path", finalpath);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
if (Common.downloadChkLogout) {
// Changed on saturday 9th nov
//if (Common.isDownloadProgress) {
if (stopped) {
break;
}
total += count;
Bundle resultData = new Bundle();
resultData.putInt("progress",
(int) (total * 100 / lenghtOfFile));
bean.setProgress((int) (total * 100 / lenghtOfFile));
rec.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
}
success = true;
//}
output.flush();
output.close();
input.close();
} catch (Exception ex) {
ex.printStackTrace();
mError = "Download Failed";
System.out.println("Net Disconnect;:" + mError);
Toast.makeText(getApplicationContext(), mError,
Toast.LENGTH_LONG).show();
}
编辑:
public void onClick(DialogInterface dialog,int id) {
Log.i("Aftr before service stopped---->>>>>", "true");
Log.i("Intent obj","Intent check..."+intent);
if(intent!=null)
{
Common.isDownloadProgress = false;
stopService(intent);
这是我的取消点击
我已经发布了启动服务的代码,并在 onHandleIntent 上下载了部分提前谢谢:)