【发布时间】:2015-03-23 12:33:11
【问题描述】:
我实现了从 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();
}
}
});
}
}
}
谢谢...
【问题讨论】:
-
当前代码有什么问题?
-
@ρяσѕρєяK 问题不存在,但我不知道如何添加它
-
如果你真的想要
ProgressBar,那么你很可能想在doInBackground()中使用publishProgress()并实现onProgressUdpate() -
@codeMagic 检查与此相关的新 so 线程。
标签: android file android-asynctask download