在这里,我举一个如何从服务器下载图像文件的示例。我假设在您的本地服务器上有一个图片文件夹,并且您正在从中下载图片..使用以下代码可能会对您有所帮助..
public class DownloadType1 extends Activity{
String dwnload_file_path = "http://10.0.2.2/pictures/webicon.PNG";
String dest_file_path = Environment.getRootDirectory()+"/pictures/img1.png";
ProgressDialog dialog = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.download1);
}
public void onClick(View v) {
dialog = ProgressDialog.show(DownloadType1.this, "", "Downloading file...", true);
new Thread(new Runnable() {
public void run() {
downloadFile(dwnload_file_path, dest_file_path);
}
}).start();
}
public void downloadFile(String url, String dest_file_path) {
try {
File dest_file = new File(dest_file_path);
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
fos.write(buffer);
fos.flush();
fos.close();
hideProgressIndicator();
} catch(FileNotFoundException e) {
hideProgressIndicator();
return;
} catch (IOException e) {
hideProgressIndicator();
return;
}
}
void hideProgressIndicator(){
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
}