##开源项目XUtils实现多线程下载
代码:
import java.io.File;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText et_path;
private EditText et_threadCount;
private static int threadCount = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path = (EditText) findViewById(R.id.et_path);
et_threadCount = (EditText) findViewById(R.id.et_threadCount);
}
public void download(View view){
String path = et_path.getText().toString().trim();
String tcStr = et_threadCount.getText().toString().trim();
if(TextUtils.isEmpty(path)){
Toast.makeText(this, "请输入下载文件的网络路径", 0).show();
return;
}else{
if(!TextUtils.isEmpty(tcStr)){
threadCount = Integer.parseInt(tcStr);
}
HttpUtils http = new HttpUtils();
http.download(path,
Environment.getExternalStorageDirectory()
+"/temp.exe", new RequestCallBack<File>() {
@Override
public void onStart() {
Toast.makeText(MainActivity.this, "开始下载...", 0).show();
}
@Override
public void onLoading(long total, long current,
boolean isUploading) {
System.out.println(current+"/"+total+"-------------");
}
@Override
public void onFailure(HttpException arg0, String arg1) {
Toast.makeText(MainActivity.this, "下载失败...", 0).show();
}
@Override
public void onSuccess(ResponseInfo<File> arg0) {
Toast.makeText(MainActivity.this,
"下载完成,文件保存在"
+arg0.result.getPath(), 0).show();
}
});
}
}
开源项目XUtils实现多线程下载
最新推荐文章于 2024-04-23 09:33:00 发布