我实现了从url下载文件的代码,工作正常(我使用asynctask下载文件)。
现在我想在下载中添加进度条,我经历了一些线程,发现我需要实现protected void onPreExecute()
& protected void onPostExecute()
。我做了第一部分。如何使用我的示例实现protected void onPostExecute()
。
我的完整主动性如下
public class MainActivity extends ActionBarActivity {
private ProgressDialog pdia;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void download(View v)
{
Log.i("download...", "download");
new DownloadFile().execute("http://10.0.2.2/filedemo/file1.pdf", "myfile1.pdf");
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DownloadFile extends AsyncTask<String, Void, Void>{
@Override
protected void onPreExecute(){
super.onPreExecute();
pdia = new ProgressDialog(getApplicationContext());
pdia.setMessage("Downloading...");
pdia.show();
}
@Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0]; // -> url to file
String fileName = strings[1]; // -> myfile.pdf
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "myapplication");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
return null;
}
protected void onPostExecute(Void result) {
//called on ui thread
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (pdia != null) {
pdia.dismiss();
}
}
});
}
}
}
谢谢......