我想使用异步任务取消下载文件,我尝试下面的代码,这里isCancelled()方法不起作用,可以任何一个建议我怎么能停止下载。
vid1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
down d1=new down();
if(vid1.getText().toString().equals("Start")){
Log.v("Vid 1", "Vid 1");
vid1.setText("Pause");
d1.execute(url1,"one");
}else if(vid1.getText().toString().equals("Pause")){
vid1.setText("Start");
Log.v("Vid 1 Else", "Vid 1 Else");
if(d1!=null && d1.getStatus()!=AsyncTask.Status.FINISHED){
d1.cancel(true);
}
}
}
});
vid2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.v("Vid 2", "Vid 2");
// TODO Auto-generated method stub
down d2=new down();
if(vid2.getText().toString().equals("Start")){
vid2.setText("Pause");
d2.execute(url2,"two");
}else if(vid2.getText().toString().equals("Pause")){
vid2.setText("Start");
Log.v("Vid 2 Else", "Vid 2 Else ");
d2.cancel(true);
}
}
});
}
private class down extends AsyncTask<String, Void, String>{
RandomAccessFile output ;
boolean cancel=false;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Log.v("Pre Execute", "Pre Execute");
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
File outputFileCache=new File(Environment.getExternalStorageDirectory()+"/pau/"+params[1]+".mp4");
try {
Long download_ok = null ;
int fileLength;
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection() ;
if (outputFileCache.exists())
{
Log.v(">>>>>>", "Exists");
connection.setAllowUserInteraction(true);
connection.setRequestProperty("Range", "bytes=" + outputFileCache.length() + "-");
}
connection.setConnectTimeout(14000);
connection.setReadTimeout(20000);
connection.connect();
if (connection.getResponseCode() / 100 != 2)
throw new Exception("Invalid response code!");
else
{
String connectionField = connection.getHeaderField("content-range");
if (connectionField != null)
{
String[] connectionRanges = connectionField.substring("bytes=".length()).split("-");
download_ok = Long.valueOf(connectionRanges[0]);
Log.v("download ok", ""+download_ok);
}
if (connectionField == null && outputFileCache.exists())
outputFileCache.delete();
if(download_ok==null){
download_ok=(long) 0;
}
fileLength = (int) (connection.getContentLength() + download_ok);
Log.v("file length", ""+fileLength);
input = new BufferedInputStream(connection.getInputStream());
output = new RandomAccessFile(outputFileCache, "rw");
output.seek(download_ok);
byte data[] = new byte[1024];
int count = 0;
int __progress = 0;
while ((count = input.read(data, 0, 1024)) != -1 && __progress!=100)
{
Log.v(">>>>>>>>>>>progress cancelled", "<<<<<<<<<"+isCancelled());
if(isCancelled()){
Log.v(">>>>>>>>>>>>>>>>>>>>>>>>>>>", "<<<<<<<<<"+isCancelled());
break;
}else{
download_ok += count;
output.write(data, 0, count);
__progress = (int) ((download_ok * 100) / fileLength);
}
}
output.close();
input.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
答案 0 :(得分:1)
发现您的问题:您每次点击都会创建一个新的Asynctask实例,例如
down d2=new down();
这意味着您在另一个AsyncTask对象上调用cancel。您需要将此行移动到开始点击的检查中,并且还使用字段而不是本地变量,即。
if(vid2.getText().toString().equals("Start")) {
d2 = new down();
vid2.setText("Pause");
d2.execute(url2,"two");
}
在您的班级中设置d2。另请注意,班级名称应始终以大写字母开头,即class Down
而不是class down
。
您可以将Asynctask存储在一个长度与视频数量相等的全局类数组中。
Down downTasks[] = new Down[TOTAL VIDEOS];
然后你初始化视图,类似于你已经做过的,这里显示了一个View
vid1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(vid1.getText().toString().equals("Start")){
Log.v("Vid 1", "Vid 1");
vid1.setText("Pause");
downTasks[0] = new down();
downTasks[0].execute(url1,"one");
}
else if(vid1.getText().toString().equals("Pause")){
vid1.setText("Start");
Log.v("Vid 1 Else", "Vid 1 Else");
if(downTasks[0]!=null && downTasks[0].getStatus()!=AsyncTask.Status.FINISHED){
downTasks[0].cancel(true);
}
}
}
});
请注意,这段代码非常多余,因为您为每个View
重写了几乎完全相同的代码,这可以通过for
循环很好地重构,但我将其作为练习留给您,如果你觉得这样。