你没有新起一个线程来下载文件,造成堵塞主线程。只有下载完毕才会更新ui
public class AndroidTest extends Activity {
private static final String TAG = "AndroidTest"; private ProgressBar progressBar = null;
private Button startButton = null;
private EditText filenameText = null;
private MyHandler handler = null; private Message message = null;
private boolean flag = true;
private int size = 1;
private int hasRead = 0;
private int len = 0;
private byte buffer[] = new byte[1024*4];
private int index = 0; 

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

progressBar = (ProgressBar)findViewById(R.id.progress_horizontal);
startButton = (Button)findViewById(R.id.mybutton);
startButton.setOnClickListener(new ButtonClick());

filenameText = (EditText)findViewById(R.id.fileNameID);

handler = new MyHandler();
}
public boolean downloadFile(final String urlStr, final String filename) {
new Thread(new Runnable(){  
public void run() { 
try {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
size = connection.getContentLength();
InputStream inputStream = connection.getInputStream();
OutputStream outputStream = new FileOutputStream(Environment.getExternalStorageDirectory()+"/"+filename);

while((len=inputStream.read(buffer))!=-1){
outputStream.write(buffer);
hasRead+=len;
index = (int)(hasRead*100)/size;
message = new Message();
message.what = 1;
handler.sendMessage(message);
Log.d(TAG, "index = " + index);
System.out.println("has = "+hasRead+" size = "+size+" index = "+index);
}

inputStream.close();
outputStream.close();
} catch (Exception e) {
flag = false;
e.printStackTrace();
}
}
}).start();

return flag;
} class ButtonClick implements OnClickListener { public void onClick(View v) {

String url = filenameText.getText().toString();
String filename = url.substring(url.lastIndexOf('/') + 1);
Log.d(TAG, "url = " + url);
Log.d(TAG, "filename = " + filename);

if(!downloadFile(url, filename)) {
String rs = "下载失败 ";
Toast.makeText(AndroidTest.this, rs, Toast.LENGTH_SHORT).show();
}

} } class MyHandler extends Handler{ @Override
public void handleMessage(Message msg) {
if (msg.what == 1) {
progressBar.setProgress(index);
Log.d(TAG, "setProgress index:" + index);
if (index >= 99) {
String rs = "下载完成";
Toast.makeText(AndroidTest.this, rs, Toast.LENGTH_SHORT).show();
}
}

super.handleMessage(msg);
} }}

解决方案 »

  1.   

    现在我知道了,感谢ameyume的相助,我新起了个线程下载,可是下载完成后我要关闭进度条怎么办?
      

  2.   

    progressBar.setVisibility(View.GONE);移走不显示进度条就可以了。
      

  3.   

    不能在非UI线程操作UI线程中的控件。
      

  4.   

    [Quote=引用 6 楼 ameyume 的回复:]
    引用 5 楼 aquan12345678 的回复:
    但是我想在子线程(非ui线程)中设置,比如那个下载完成之后我想设置成不显示,可是会出错不能在非UI线程操作UI线程中的控件。
    [/Quot好像可以用消息处理函数Handler吧