在Dialog或DialogFragment中使用
例子
public class DownloadDialog extends AbsDialog implements View.OnClickListener {
private HorizontalProgressBarWithNumber mPb;
private Button mStart;
private Button mCancel;
private TextView mSize;
private TextView mSpeed;
private long mTaskId = -1;
private static final String DOWNLOAD_URL =
"http://static.gaoshouyou.com/d/4b/d7/e04b308d9cd7f0ad4cac18d1a514544c.apk";
public DownloadDialog(Context context) {
super(context);
init();
}
@Override protected int setLayoutId() {
return R.layout.dialog_download;
}
private void init() {
Aria.download(this).register();
mPb = findViewById(R.id.progressBar);
mStart = findViewById(R.id.start);
mCancel = findViewById(R.id.cancel);
mSize = findViewById(R.id.size);
mSpeed = findViewById(R.id.speed);
DownloadEntity entity = Aria.download(this).getFirstDownloadEntity(DOWNLOAD_URL);
if (entity != null) {
mSize.setText(CommonUtil.formatFileSize(entity.getFileSize()));
int p = (int) (entity.getCurrentProgress() * 100 / entity.getFileSize());
mPb.setProgress(p);
int state = entity.getState();
setBtState(state != DownloadEntity.STATE_RUNNING);
mTaskId = entity.getId();
} else {
setBtState(true);
}
mStart.setOnClickListener(this);
mCancel.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.start:
if (mTaskId == -1) {
mTaskId = Aria.download(this)
.load(DOWNLOAD_URL)
.setFilePath(Environment.getExternalStorageDirectory().getPath() + "/飞机大战.apk")
.create();
mStart.setText(getContext().getString(R.string.stop));
break;
}
if (Aria.download(this).load(mTaskId).isRunning()) {
Aria.download(this).load(mTaskId).stop();
mStart.setText(getContext().getString(R.string.resume));
} else {
Aria.download(this).load(mTaskId).resume();
mStart.setText(getContext().getString(R.string.stop));
}
break;
case R.id.cancel:
Aria.download(this).load(mTaskId).cancel();
mTaskId = -1;
mStart.setText(getContext().getString(R.string.start));
break;
}
}
@Download.onTaskPre public void onTaskPre(DownloadTask task) {
mSize.setText(CommonUtil.formatFileSize(task.getFileSize()));
setBtState(false);
}
@Download.onTaskStop public void onTaskStop(DownloadTask task) {
setBtState(true);
mSpeed.setText(task.getConvertSpeed());
}
@Download.onTaskCancel public void onTaskCancel(DownloadTask task) {
setBtState(true);
mPb.setProgress(0);
mSpeed.setText(task.getConvertSpeed());
}
@Download.onTaskRunning public void onTaskRunning(DownloadTask task) {
if (task.getKey().equals(DOWNLOAD_URL)) {
mPb.setProgress(task.getPercent());
mSpeed.setText(task.getConvertSpeed());
}
}
@Override protected void dataCallback(int result, Object obj) {
}
private void setBtState(boolean startEnable) {
mStart.setEnabled(startEnable);
mCancel.setEnabled(!startEnable);
}
}
如上,如果你已经对Dialog对象设置了OnDismissListener
或OnCancelListener
事件,那么Aria将无法跟踪Dialog的生命周期;
这时你需要在Dialog的Dismiss
手动取消Aria的注册
@Override public void dismiss() {
super.dismiss();
Aria.download(this).unRegister();
}