我创建了一个应用程序,其中有 5 个按钮用于流式传输 5 个不同的直播频道。除了 5 个按钮,我还有一个进度条(环)。我正在使用进度条,因为视频需要时间来加载。我在 AsyncTask 的 onBackground() 中编写了主要代码,它返回一些在按钮的单击事件中调用的值。由于所有 5 个按钮都分配了不同的 url,我如何为所有 5 个按钮使用相同的 onBackground()?在这种情况下该怎么办?谁能给我一个很好的例子。
问问题
135 次
2 回答
0
onBackground()
是 AsyncTask 的一部分。它与按钮或其他 UI 元素没有任何共同之处。如果您想重用代码,只需将您的 UI 作为参数传递给 AsyncTask 构造函数,然后在需要时使用它。
于 2013-03-20T06:21:06.823 回答
0
Video Path
私有静态字符串 file_url = "url";
in your activity
新的 DownloadFileFromURL().execute(file_url);
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
Background Async Task to download file
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/demo.mp4");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
// Displaying downloaded video into video view
// Reading image path from sdcard
String videopath = Environment.getExternalStorageDirectory()
.toString() + "/demo.mp4";
// setting downloaded into image view
}
}
于 2013-03-20T06:23:03.507 回答