我第一次使用AsyncTask类作为主活动类中的内部类。 这是代码:
// Async Task Class
class fetchdata extends AsyncTask<String, String, String> {
// Show Progress bar before downloading file
@Override
protected void onPreExecute() {
super.onPreExecute();
// Shows Progress Bar Dialog and then call doInBackground method
showDialog(progress_bar_type);
}
// Download File from Internet
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// Get Music file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),10*1024);
// Output stream to write file in SD card
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/jai_ho.mp3");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// Publish the progress which triggers onProgressUpdate method
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// Write data to file
output.write(data, 0, count);
}
// Flush output
output.flush();
// Close streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
// While Downloading File
protected void onProgressUpdate(String... progress) {
// Set progress percentage
prgDialog.setProgress(Integer.parseInt(progress[0]));
}
// Once File is downloaded
@Override
protected void onPostExecute(String file_url) {
// Dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
Toast.makeText(getApplicationContext(), "Download complete", Toast.LENGTH_LONG).show();
// Play the music
}
}
Eclipse告诉我不推荐使用showDialog和dismissDialog方法。 如何使用FragmentManager使用DialogFragment类更改我的代码?
答案 0 :(得分:1)
根据需要进行更改(例如参数,返回类型):
private class getData extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
progressDialog = new ProgressDialog(activityName.this);//getApplicationContext()
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Making a request to url and getting response
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (progressDialog.isShowing())
progressDialog.dismiss();
/**
* To do code
* */
}
}
在主课程开始后添加以下行:
private ProgressDialog processDialog;