基本的下载示例代码应该是这样的:
private class DownloadWallpaperTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String wallpaperURLStr = params[0];
String localPath = Integer.toString(wallpaperURLStr.hashCode());
try {
URL wallpaperURL = new URL(wallpaperURLStr);
URLConnection connection = wallpaperURL.openConnection();
//get file length
int filesize = connection.getContentLength();
if(filesize < 0) {
downloadProgressDialog.setMax(1000000);
} else {
downloadProgressDialog.setMax(filesize);
}
InputStream inputStream = new BufferedInputStream(wallpaperURL.openStream(), 10240);
String appName = getResources().getString(R.string.app_name);
OutputStream outputStream = openFileOutput(localPath, Context.MODE_PRIVATE);
byte buffer[] = new byte[1024];
int dataSize;
int loadedSize = 0;
while ((dataSize = inputStream.read(buffer)) != -1) {
loadedSize += dataSize;
publishProgress(loadedSize);
outputStream.write(buffer, 0, dataSize);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return localPath;
}
protected void onProgressUpdate(Integer... progress) {
downloadProgressDialog.setProgress(progress[0]);
}
protected void onPostExecute(String result) {
downloadProgressDialog.hide();
//open preview activity
Bundle postInfo = new Bundle();
postInfo.putString("localpath", result);
if (previewPanelIntent == null) {
previewPanelIntent = new Intent(MainActivity.this,
PreviewPanel.class);
}
previewPanelIntent.putExtras(postInfo);
startActivity(previewPanelIntent);
}
}
要获取更多信息,我在我的应用程序中使用了一个 android 应用程序源代码:
Android 下载带进度条的图片