老师,我的程序能运行,但无法下载图片,logcat也不报错
//源码如下:
public class Download {
private Handler handler;
public Download(Handler handler){
this.handler = handler;
}
//创建线程池
private Executor threadPool =Executors.newFixedThreadPool(3);
static class DownloadRunnable implements Runnable{
private String url;
private String fileName;
private long start;
private long end;
private Handler handler;
public DownloadRunnable(String url,String fileName,long start,long end,Handler handler){
this.url = url;
this.fileName = fileName;
this.start = start;
this.end = end;
this.handler = handler;
}
@Override
public void run() {
try {
URL httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setReadTimeout(5000);
conn.setRequestProperty("Range", "bytes="+start+"-"+end);
conn.setRequestMethod("GET");
RandomAccessFile access = new RandomAccessFile(new File(fileName),"rwd");
access.seek(start);
InputStream in = conn.getInputStream();
byte[] b = new byte[1024*4];
int len=0;
while((len = in.read(b))!=-1){
access.write(b, 0, len);
}
if(access!=null){
access.close();
}
if(in!=null){
in.close();
}
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
} catch (Exception e) {
}
}
}
public void downloadFile(String url){
try {
URL httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
int count = conn.getContentLength();
int block = count/3;
String fileName = getFileName(url);
File parent = Environment.getExternalStorageDirectory();
File fileDownload = new File(parent,fileName);
/**
* 此算法为每个线程分配下载的文件量,其中最后一个线程下载剩下的全部文件
* 文件块从0开始算起
*/
for(int i=0;i<3;i++){
long start = i*block;
long end = (i+1)*block-1;
if(i==2){
end = count;
}
DownloadRunnable runnable = new DownloadRunnable(url,fileDownload.getAbsolutePath(),start,end,handler);
threadPool.execute(runnable);
}
} catch (Exception e) {
}
}
public String getFileName(String url){
return url.substring(url.lastIndexOf("/")+1);
}
}
//activity类
public class DownloadActivity extends Activity {
private Button button;
private TextView textView;
private int count = 0;
private Handler handler = new Handler(){
public void handleMessage(Message msg){
int result = msg.what;
count+=result;
if(count==3){
textView.setText("下载成功");
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.down);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new Thread(){
@Override
public void run() {
Download load = new Download(handler);
String url = "http://192.168.124.1:8080/PostTest/c.jpg";
load.downloadFile(url);
}
}.start();
Toast.makeText(DownloadActivity.this, Environment.getExternalStorageDirectory().toString(), Toast.LENGTH_LONG).show();
}
});
}
}实在是不知道哪里错了。。。。