基本下載示例代碼應該是這樣的:
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 Download Image with Progress Bar
請發帖l ogcat日誌..你得到什麼錯誤? – 2013-03-10 14:25:50
您是否更新AndroidManifest.xml的Internet權限? – hakiko 2013-03-10 14:27:15
是的,我這樣做的問題是我沒有得到任何錯誤 – ChoRisk 2013-03-10 14:30:17