廢話不多說,上代碼,我寫了一個提供下載地方法,只需要傳入一個url即可,
調用這個startdown方法後,就會彈出一個dialog,開始的時候,遇到了一個問題,就是我下載了一半,如果不想下載了,想取消怎麼辦,我開始用的是
dialog.dismiss();
這段代碼,但是後來發現不行啊,因爲這樣僅僅是取消了dialog,由於沒有做斷點下載,所以在想怎麼取消這個線程,阻止下載,修改代碼
在請求okhttputils的時候,給它加上一個tag,然後看看裏面的取消的源碼
然後再取消的裏面調用了一下,好了,阻止了下載了,大牛勿噴,新手筆記...
public void startdown(final String urls) { final ProgressDialog dialog = new ProgressDialog(mContext); dialog.setTitle("正在下載"); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(false); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); OkHttpUtils.getInstance().cancelTag(urls); } }); dialog.show(); Callback call=new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "down") { @Override public void onError(Call call, Exception e, int id) { } @Override public void inProgress(float progress, long total, int id) { super.inProgress(progress, total, id); dialog.setProgress((int) (100 * progress)); } @Override public void onResponse(File response, int id) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.setDataAndType(Uri.fromFile(response), "application/vnd.android.package-archive"); ((Activity)mContext).startActivityForResult(intent,0); } }; OkHttpUtils .get().tag(urls) .url(urls) .build() .execute(call);