final AlertDialog d = new AlertDialog.Builder(youclassname.this)
.setView(input)
.setTitle(R.string.message)
.setPositiveButton(android.R.string.ok,
new Dialog.OnClickListener() {
public void onClick(DialogInterface d, int which) {
//Do nothing here. We override the onclick
}
})
.setNegativeButton(android.R.string.cancel, null)
.create();
d.setOnShowListener(new DialogInterface.OnShowListener() {
public void onShow(DialogInterface dialog) {
Button b = d.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startDownload();//begin downloading
d.dismiss();
}
});
}
});
d.show();
这是开始下载部分。
private void startDownload() {
String url ="file download link";
Toast.makeText(dwn.this, url,Toast.LENGTH_LONG).show();
new DownloadFileAsync().execute(url);
}
这是异步任务
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 conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/file.type");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
}
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);
}
}
这是进度对话框的代码
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading PDF file");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}