我有一个通过互联网下载文件的应用程序。该应用程序开始下载但不知道如何显示进度条。 以下适配器类:
public class UpdateListViewAdapter extends BaseAdapter
{
// Declare Variables
private LayoutInflater inflater;
private ArrayList<ApplicationPojo> applicationList = null;
private Activity activity;
private ViewHolder holder;
private String logoName;
private PackageManager pm;
private ApkUpdater downloader;
private ListView listView;
public UpdateListViewAdapter(Activity activity, ArrayList<ApplicationPojo> applicationList,ListView listView)
{
this.activity = activity;
this.applicationList = applicationList;
this.inflater = LayoutInflater.from(activity);
downloader = new ApkUpdater(activity);
this.listView = listView;
}
@Override
public int getCount() {
return applicationList.size();
}
@Override
public ApplicationPojo getItem(int position) {
return applicationList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent)
{
if (view == null)
{
holder = new ViewHolder();
view = inflater.inflate(R.layout.singleapp, null);
holder.openInstalledAppBtn = (ImageView) view.findViewById(R.id.openInstalledApp);
holder.downloadBtn = (ImageView) view.findViewById(R.id.updateApp);
holder.progressBar = (ProgressBar)view.findViewById(R.id.updateProgress);
holder.cancelBtn = (ImageView) view.findViewById(R.id.cancel);
holder.appName = (TextView) view.findViewById(R.id.appName);
holder.developer = (TextView) view.findViewById(R.id.developer);
holder.size = (TextView) view.findViewById(R.id.size);
holder.appCat = (TextView) view.findViewById((R.id.appCat));
holder.installBtn = (ImageView) view.findViewById(R.id.install);
holder.removeBtn = (ImageView) view.findViewById(R.id.remove);
holder.catlogo = (ImageView) view.findViewById(R.id.catlogo);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
try
{
final View finalView = view;
holder.logo = (ImageView) finalView.findViewById(R.id.appLogo);
logoName = applicationList.get(position).getLogo();
Picasso.with(activity)
.load(IPClass.SERVERIP + logoName)
.into(holder.logo);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String appid = applicationList.get(position).getId();
int category = applicationList.get(position).getCategory();
Intent rec1Intent = new Intent(activity, AppView.class);
rec1Intent.putExtra("section","update");
activity.startActivity(rec1Intent);
AppView appView = new AppView();
appView.setParameters(appid, category);
try
{
UpdateList.updateAdapter.notifyDataSetChanged();
} catch (Exception ex) {
}
}
});
final String id = applicationList.get(position).getId();
final String path = applicationList.get(position).getPath();
final String fileName = applicationList.get(position).getFileName();
final String name = applicationList.get(position).getName();
final String developer = applicationList.get(position).getDeveloper();
final double size = applicationList.get(position).getSize();
final String logo = applicationList.get(position).getLogo();
final int category = applicationList.get(position).getCategory();
holder.progressBar.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.GONE);
holder.installBtn.setVisibility(View.GONE);
holder.openInstalledAppBtn.setVisibility(View.GONE);
holder.downloadBtn.setVisibility(view.VISIBLE);
holder.downloadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
holder.downloadBtn.setVisibility(View.GONE);
holder.progressBar.setVisibility(View.VISIBLE);
holder.cancelBtn.setVisibility(View.VISIBLE);
holder.cancelBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
downloader.cancelDownload(name);
holder.cancelBtn.setVisibility(View.GONE);
holder.downloadBtn.setVisibility(View.VISIBLE);
}
});
new ApkUpdater(activity).setParameters(path, fileName, name);
UpdateList.updateAdapter.notifyDataSetChanged();
}
});
}
}
catch (Exception ex)
{
Log.d("Adapter Exception", ex.toString());
}
return view;
}
public class ViewHolder
{
ImageView logo;
TextView appName;
TextView developer;
ImageView downloadBtn;
ImageView installBtn;
ImageView openInstalledAppBtn;
ImageView cancelBtn;
ImageView catlogo;
ImageView removeBtn;
ProgressBar progressBar;
TextView appCat;
TextView size;
}
}
以下是下载文件的类:
public class ApkUpdater extends Activity
{
///////////////////////////////////--------DECLARE VARIABLES-------------------///////////////////////////
private Activity downloadActivity;
private static DownloadManager manager;
private String name;
private String path;
private String fileName;
private long downloadId;
private ProgressBar progressBar;
private ImageView cancelBtn;
private ImageView installBtn;
private int bytes_downloaded;
public static volatile int dl_progress;
public static volatile boolean downloading;
public static volatile boolean downloadInProgress = true;
private Cursor cursor;
//-------------------MAP TO STORE APP NAME WITH DOWNLOADED DATA SIZE-----//
public static HashMap<String, Integer> applicationUpdateList = new HashMap();
//-------------------MAP TO STORE APP NAME WITH DOWNLOAD ID--------------//
public static HashMap<String, Long> updateIdList = new HashMap();
//-------------------MAP TO STORE APP NAME WITH PACKAGE FILE------------//
public static HashMap<String, String> getUpdateFileName = new HashMap<>();
public ApkUpdater(Activity activity){ downloadActivity = activity; }
//---------------------------FUNCTION TO GET PARAMETERS AND SET ------------------------------//
public void setParameters(String path, String fileName, String name)
{
this.path = path;
this.fileName = fileName;
this.name = name;
File directory = new File(Environment.getExternalStorageDirectory() + "/Android/appdata/tmp/dl/");
if(!directory.exists())
{
directory.mkdirs();
}
startDownload();
}
///////////////////////////////////--------DOWNLOAD STARTS HERE-----------///////////////////////////
public void startDownload() {
try
{
String url = IPClass.SERVERIP + path;
String fileToDownload = url + "/" + fileName;
DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(fileToDownload));
downloadRequest.setTitle("Downloading... " + name);
downloadRequest.setDescription(name);
downloadRequest.allowScanningByMediaScanner();
downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadRequest.setDestinationInExternalPublicDir("/Android/appdata/tmp/tmpdl/", fileName);
manager = (DownloadManager) downloadActivity.getSystemService(Context.DOWNLOAD_SERVICE);
downloadId = manager.enqueue(downloadRequest);
applicationUpdateList.put(name, 0);
updateIdList.put(name, downloadId);
getUpdateFileName.put(name, fileName);
getUpdateData();
}
catch (Exception ex)
{
Log.d("Downloader: ", ex.toString());
}
}
///////////////////////////////////--------A THREAD TO CONTROL DOWNLOAD AND PROGRESS BAR -----------///////////////////////////
public void getUpdateData()
{
new Thread(new Runnable()
{
@Override
public void run()
{
int appSizeInBytes;
while (applicationUpdateList.containsKey(name))
{
try
{
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadId);
cursor = manager.query(q);
cursor.moveToFirst();
bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
appSizeInBytes = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
dl_progress = (int)((bytes_downloaded * 100L)/appSizeInBytes);
applicationUpdateList.put(name,dl_progress);
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL){downloadSuccessful();}
else if(status == DownloadManager.STATUS_FAILED){ downloadFailed();}
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
cursor.close();
}
}
}
}).start();
}
public void downloadFailed()
{
manager.remove(downloadId);
File deleteFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Android/appdata/tmp/tmpdl/" + fileName);
deleteFile.delete();
}
public void downloadSuccessful()
{
applicationUpdateList.remove(name);
downloadInProgress = false;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/Android/appdata/tmp/dl/" + fileName)), "application/vnd.android.package-archive");
downloadActivity.startActivity(intent);
}
}
现在我坚持如何更新进度条! 任何想法
答案 0 :(得分:0)
如果要在listview中显示Progressbar,请在Adapter类中输入Progressbar并为特定位置调用Asyntask
<强> DownloadTask 强>
public class DownloadTask extends AsyncTask<String, Integer, String> {
String status = "";
String erroMessage = "";
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
showprogresslayout.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
JSONObject json;
//put start download code here
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
@Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
return erroMessage;
}
@Override
protected void onProgressUpdate(Integer... progress) {
// TODO Auto-generated method stub
super.onProgressUpdate(progress);
progressBar.setProgress(progress[0]);
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
showprogresslayout.setVisibility(View.GONE);
}
}
<强> AndroidMultiPartEntity.java 强>
public class AndroidMultiPartEntity extends MultipartEntity
{
private final ProgressListener listener;
public AndroidMultiPartEntity(final ProgressListener listener) {
super();
this.listener = listener;
}
public AndroidMultiPartEntity(final HttpMultipartMode mode,
final ProgressListener listener) {
super(mode);
this.listener = listener;
}
public AndroidMultiPartEntity(HttpMultipartMode mode,
final String boundary, final Charset charset,
final ProgressListener listener) {
super(mode, boundary, charset);
this.listener = listener;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
super.writeTo(new CountingOutputStream(outstream, this.listener));
}
public static interface ProgressListener {
void transferred(long num);
}
public static class CountingOutputStream extends FilterOutputStream {
private final ProgressListener listener;
private long transferred;
public CountingOutputStream(final OutputStream out,
final ProgressListener listener) {
super(out);
this.listener = listener;
this.transferred = 0;
}
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
this.transferred += len;
this.listener.transferred(this.transferred);
}
public void write(int b) throws IOException {
out.write(b);
this.transferred++;
this.listener.transferred(this.transferred);
}
}
}
<强> showprogresslayout.xml 强>
<LinearLayout
android:id="@+id/showprogresslayout"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_below="@+id/ln_video"
android:layout_gravity="center"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:orientation="vertical"
android:visibility="gone" >
<LinearLayout
android:id="@+id/ln_txt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:orientation="horizontal" >
<com.elizibles.fonts.MyHelveticalTextview
android:id="@+id/txtuploading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Uploading.."
android:textColor="@color/orange"
android:textSize="16sp" />
<com.elizibles.fonts.MyHelveticalTextview
android:id="@+id/txtPercentage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="0%"
android:textColor="@color/orange"
android:textSize="16sp" />
</LinearLayout>
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="20dp"
android:layout_marginBottom="35dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp" />
</LinearLayout>