我正在尝试从API下载zip文件。为此,我使用以下代码:
public class Download_Activity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download);
startBtn = (Button) findViewById(R.id.downloadButton);
startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
String url = downloadURL;
new DownloadFileAsync().execute(url);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.connect();
Log.i("1111", "1111" );
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot, "hello1.zip");
Log.i("2222", "2222" );
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
Log.i("3333", "3333" );
Log.i("befferLength", "bufferLength: " + bufferLength);
Log.i("is read buffer", "is read buffer: " + inputStream.read(buffer));
while ((bufferLength = inputStream.read(buffer)) > 0) {
Log.i("inside while", "inside while ");
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
updateProgress(downloadedSize, totalSize);
}
Log.i("4444", "4444" );
fileOutput.close();
} catch (Exception e) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
public void updateProgress(int currentSize, int totalSize) {
Toast.makeText(getApplicationContext(), "Loading Files...",
Toast.LENGTH_SHORT).show();
}
在此代码中,zip文件创建为“hello1.zip”,但此文件在我的手机中为空。这里我有各种日志语句来查找代码的执行。令我惊讶的是“Log.i(”2222“,”2222“);”在打印其余日志时打印。你能告诉我问题是什么吗?
提前致谢..!
答案 0 :(得分:0)
U可以使用DownloadManager类来处理暂停并在网络可用的情况下继续下载,并且您可以运行广播接收器以在下载完成时执行操作(如推送通知等) http://developer.android.com/reference/android/app/DownloadManager.html