如何在片段中使用异步任务下载进度对话框?
How to use Asynchronous task for download progress dialog in fragment?
在我的应用程序中,当我单击文件时,它将开始从服务器下载,进度将显示在 phone 状态 bar.But 我希望进度条显示在我的应用程序屏幕本身上。
我关注了这个 link :-
http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/
在处理问题陈述时,我遇到了这些 SYSTEM_DOWNLOADER
和 APP_DOWNLOADER
.
这些到底是做什么的?
上面的例子是在activity.I中调用的,想知道如何在片段中调用带有下载进度条的异步任务。
我正在编辑问题以进行澄清,请帮忙
convertView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
MoodleModule module = listObjects.get(position).module;
if (module == null)
return;
Intent i = new Intent(context, AppBrowserActivity.class);
String modurl = module.getUrl();
String courseurl = session.getmUrl()
+ "/course/view.php?id=" + courseid;
modurl = (modurl == null) ? courseurl : modurl;
i.putExtra("url", modurl);
if (!module.getModname().contentEquals("resource")) {
context.startActivity(i);
return;
}
if (module.getContents() == null) {
context.startActivity(i);
return;
}
if (module.getContents().isEmpty()) {
context.startActivity(i);
return;
}
MoodleModuleContent content = module.getContents().get(0);
String path = "/s" + session.getCurrentSiteId() + "c"
+ courseid + "/";
File file = new File(Environment
.getExternalStoragePublicDirectory("/MDroid")
+ path + content.getFilename());
//TODO here
// Download if file doesn't already exist
if (!file.exists()) {
String fileurl = content.getFileurl();
fileurl += "&token=" + session.getToken();
fName=content.getFilename();
//FROM HERE I AM CALLING ASYNCHRONOUS TASK
startDownload();
} else {
FileOpener.open(context, file);
}
}
});
return convertView;
}
private void startDownload() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
new DownloadFileAsync().execute(url);
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
/*mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Downloading file.");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();*/
/*showDialog(DIALOG_DOWNLOAD_PROGRESS);*/
mProgressDialog.show();
}
@Override
protected String doInBackground(String... aurl) {
int count;
/*String fName=content.getFilename();*/
/*InputStream input = null;
OutputStream output = null;*/
HttpURLConnection connection = null;
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);
/* File f = new File(Environment.getExternalStorageDirectory()
+ "/sdcard/");
f.mkdirs();*/
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg");
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) {}
return null;
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
/* mProgressDialog.dismiss();*/
}
@Override
protected void onPostExecute(String unused) {
/*dismissDialog(DIALOG_DOWNLOAD_PROGRESS);*/
mProgressDialog.dismiss();
}
}
当我点击文件时,应用程序会强制执行 stop.what 我在做什么错误?请帮助我 out.thanks
我在 own.Hope 上找到了答案,它对任何人都有帮助。
我想在片段中调用异步任务,并想显示进度对话框,它将以百分比显示下载文件的进度。
1> 我在 class 中调用了异步任务。
DownloadTask.java class
//This is important
public DownloadTask(Context context) {
this.context = context;
mProgressDialog = new ProgressDialog(context);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCanceledOnTouchOutside(false);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void download(String fileUrl, String filepath, String fileName,
Boolean visibility, Boolean choice) {
// Make directories if required
this.fileUrl=fileUrl;
this.filepath=filepath;
this.fileName=fileName;
this.visibility=visibility;
File f = new File(
Environment.getExternalStoragePublicDirectory("/MDroid")
+ filepath);
if (!f.exists())
f.mkdirs();
if (choice == SYSTEM_DOWNLOADER) {
String url=fileUrl;
new MyAsyncTask().execute(url);
} else {
mdroidDownload(fileUrl, fileName);
reqId =0;
}
}
class MyAsyncTask extends AsyncTask<String, String, Void> {
boolean running;
@Override
protected Void doInBackground(String...fUrl) {
int count;
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(fUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
int lenghtOfFile = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(
Environment.getExternalStorageDirectory() + "/MDroid/"
+ fileName);
//#################################
mydownload(fileUrl, filepath, fileName,
visibility);
//##########################################
byte data[] = new byte[4096];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
running = true;
mProgressDialog.show();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mProgressDialog.dismiss();
}
protected void onProgressUpdate(String... progress) {
// Update the progress dialog
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
}
public long mydownload(String fileUrl,String filepath,String fileName,Boolean visibility)
{
DownloadManager manager = (DownloadManager) context
.getSystemService(Context.DOWNLOAD_SERVICE);
/* TODO- Offer better alternative. Only a temporary, quick,
* workaround for 2.3.x devices. May not work on all sites.
*/
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
fileUrl = fileUrl.replace("https://", "http://");
Request request = new Request(Uri.parse(fileUrl));
try {
request.setDestinationInExternalPublicDir("/MDroid", filepath
+ fileName);
} catch (Exception e) {
Toast.makeText(context, "External storage not found!",
Toast.LENGTH_SHORT).show();
return 0;
}
request.setTitle(fileName);
request.setDescription("MDroid file download");
// Visibility setting not available in versions below Honeycomb
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
if (!visibility)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
else
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// -TODO- save this id somewhere for progress retrieval
reqId = manager.enqueue(request);
return reqId;
}
2>我将 DownloadTask.java class 文件中的下载方法调用到我的片段 activity 中,就像这样
// Download if file doesn't already exist
if (!file.exists()) {
fileurl = content.getFileurl();
fileurl += "&token=" + session.getToken();
fName = content.getFilename();
//FROM HERE I AM CALLING ASYNCHRONOUS TASK
DownloadTask dt = new DownloadTask(context);
dt.download(fileurl, path, content.getFilename(), false,
DownloadTask.SYSTEM_DOWNLOADER);
} else {
FileOpener.open(context, file);
}
在我的应用程序中,当我单击文件时,它将开始从服务器下载,进度将显示在 phone 状态 bar.But 我希望进度条显示在我的应用程序屏幕本身上。
我关注了这个 link :-
http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/
在处理问题陈述时,我遇到了这些 SYSTEM_DOWNLOADER
和 APP_DOWNLOADER
.
这些到底是做什么的?
上面的例子是在activity.I中调用的,想知道如何在片段中调用带有下载进度条的异步任务。
我正在编辑问题以进行澄清,请帮忙
convertView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
MoodleModule module = listObjects.get(position).module;
if (module == null)
return;
Intent i = new Intent(context, AppBrowserActivity.class);
String modurl = module.getUrl();
String courseurl = session.getmUrl()
+ "/course/view.php?id=" + courseid;
modurl = (modurl == null) ? courseurl : modurl;
i.putExtra("url", modurl);
if (!module.getModname().contentEquals("resource")) {
context.startActivity(i);
return;
}
if (module.getContents() == null) {
context.startActivity(i);
return;
}
if (module.getContents().isEmpty()) {
context.startActivity(i);
return;
}
MoodleModuleContent content = module.getContents().get(0);
String path = "/s" + session.getCurrentSiteId() + "c"
+ courseid + "/";
File file = new File(Environment
.getExternalStoragePublicDirectory("/MDroid")
+ path + content.getFilename());
//TODO here
// Download if file doesn't already exist
if (!file.exists()) {
String fileurl = content.getFileurl();
fileurl += "&token=" + session.getToken();
fName=content.getFilename();
//FROM HERE I AM CALLING ASYNCHRONOUS TASK
startDownload();
} else {
FileOpener.open(context, file);
}
}
});
return convertView;
}
private void startDownload() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
new DownloadFileAsync().execute(url);
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
/*mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Downloading file.");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();*/
/*showDialog(DIALOG_DOWNLOAD_PROGRESS);*/
mProgressDialog.show();
}
@Override
protected String doInBackground(String... aurl) {
int count;
/*String fName=content.getFilename();*/
/*InputStream input = null;
OutputStream output = null;*/
HttpURLConnection connection = null;
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);
/* File f = new File(Environment.getExternalStorageDirectory()
+ "/sdcard/");
f.mkdirs();*/
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg");
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) {}
return null;
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
/* mProgressDialog.dismiss();*/
}
@Override
protected void onPostExecute(String unused) {
/*dismissDialog(DIALOG_DOWNLOAD_PROGRESS);*/
mProgressDialog.dismiss();
}
}
当我点击文件时,应用程序会强制执行 stop.what 我在做什么错误?请帮助我 out.thanks
我在 own.Hope 上找到了答案,它对任何人都有帮助。
我想在片段中调用异步任务,并想显示进度对话框,它将以百分比显示下载文件的进度。
1> 我在 class 中调用了异步任务。
DownloadTask.java class
//This is important
public DownloadTask(Context context) {
this.context = context;
mProgressDialog = new ProgressDialog(context);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCanceledOnTouchOutside(false);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void download(String fileUrl, String filepath, String fileName,
Boolean visibility, Boolean choice) {
// Make directories if required
this.fileUrl=fileUrl;
this.filepath=filepath;
this.fileName=fileName;
this.visibility=visibility;
File f = new File(
Environment.getExternalStoragePublicDirectory("/MDroid")
+ filepath);
if (!f.exists())
f.mkdirs();
if (choice == SYSTEM_DOWNLOADER) {
String url=fileUrl;
new MyAsyncTask().execute(url);
} else {
mdroidDownload(fileUrl, fileName);
reqId =0;
}
}
class MyAsyncTask extends AsyncTask<String, String, Void> {
boolean running;
@Override
protected Void doInBackground(String...fUrl) {
int count;
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(fUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
int lenghtOfFile = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(
Environment.getExternalStorageDirectory() + "/MDroid/"
+ fileName);
//#################################
mydownload(fileUrl, filepath, fileName,
visibility);
//##########################################
byte data[] = new byte[4096];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
running = true;
mProgressDialog.show();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mProgressDialog.dismiss();
}
protected void onProgressUpdate(String... progress) {
// Update the progress dialog
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
}
public long mydownload(String fileUrl,String filepath,String fileName,Boolean visibility)
{
DownloadManager manager = (DownloadManager) context
.getSystemService(Context.DOWNLOAD_SERVICE);
/* TODO- Offer better alternative. Only a temporary, quick,
* workaround for 2.3.x devices. May not work on all sites.
*/
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
fileUrl = fileUrl.replace("https://", "http://");
Request request = new Request(Uri.parse(fileUrl));
try {
request.setDestinationInExternalPublicDir("/MDroid", filepath
+ fileName);
} catch (Exception e) {
Toast.makeText(context, "External storage not found!",
Toast.LENGTH_SHORT).show();
return 0;
}
request.setTitle(fileName);
request.setDescription("MDroid file download");
// Visibility setting not available in versions below Honeycomb
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
if (!visibility)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
else
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// -TODO- save this id somewhere for progress retrieval
reqId = manager.enqueue(request);
return reqId;
}
2>我将 DownloadTask.java class 文件中的下载方法调用到我的片段 activity 中,就像这样
// Download if file doesn't already exist
if (!file.exists()) {
fileurl = content.getFileurl();
fileurl += "&token=" + session.getToken();
fName = content.getFilename();
//FROM HERE I AM CALLING ASYNCHRONOUS TASK
DownloadTask dt = new DownloadTask(context);
dt.download(fileurl, path, content.getFilename(), false,
DownloadTask.SYSTEM_DOWNLOADER);
} else {
FileOpener.open(context, file);
}