在我的项目中,我想下载用户输入的链接。 当用户输入下载链接时我想显示进度条以显示下载百分比。 在此代码中,我可以显示进度条,但它不显示下载进度。如何显示下载的百分比或进度。 以及如何在下载成功完成后完成它?
这是我的代码:
public class MyActivity extends Activity {
private long enqueue;
private DownloadManager dm;
final Context context = this;
public Button star_download, view_downlod;
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
star_download = (Button) findViewById(R.id.start_download);
view_downlod = (Button) findViewById(R.id.view_download);
star_download.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.alert_custom);
dialog.setTitle("Downloading ...");
// set the custom dialog components - text, image and button
final EditText text = (EditText) dialog.findViewById(R.id.text);
final String link = text.getText().toString();
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(text.getText().toString()));
enqueue = dm.enqueue(request);
showDialog(progress_bar_type);
}
});
dialog.show();
}
});
view_downlod.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
});
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
ImageView view = (ImageView) findViewById(R.id.imageView1);
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
view.setImageURI(Uri.parse(uriString));
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
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;
}
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
}
我是android的新手,我真的很困惑,任何人都可以帮助我吗?
答案 0 :(得分:0)
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
getActivity().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]);
Log.d("URl","Url====="+f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
extn=f_url[0].split("XYZ/");
Log.d("URlextn","Urlextn====="+extn[1]);
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// File file = new File(Environment.DIRECTORY_DOCUMENTS /);
// Output stream to write file
//OutputStream output = new FileOutputStream(Environment.getExternalStoragePublicDirectory() +extn[1]);
OutputStream output = null;
File mydir = new File(Environment.getExternalStorageDirectory() + "/xyz/");
if(!mydir.exists())
mydir.mkdirs();
output = new FileOutputStream(mydir+"/"+extn[1]);
Log.d("EXTERNAL PATH","EXTERNAL PATH===="+ Environment.getExternalStorageDirectory()+"/xyz/");
byte data[] = new byte[4096];
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);
pDialog.dismiss();
try{
imagePath = Environment.getExternalStorageDirectory()+"/"+"xyz"+"/" + extn[1];
}
catch (ArrayIndexOutOfBoundsException | NullPointerException ne)
{
System.out.println("ArrayError:" + ne);
}
System.out.println("imagePath==" + imagePath);
imgFile = new File(imagePath);
galleryAddPic(imgFile, getActivity());
}
}