Android下载带进度条

时间:2012-04-06 15:23:21

标签: android android-progressbar

如何获得getContentLength

这是我的代码:

HttpGet request = new HttpGet(MyConstants.URL);
HttpResponse response = null;
response = httpClient.execute(request);
HttpEntity httpEntity = response.getEntity();

我想让我的代码与此示例代码类似:

示例代码:

 int count;
try {
    URL url = new URL(f_url[0]);
    URLConnection conection = url.openConnection();
    conection.connect();
    // getting file length
    int lenghtOfFile = conection.getContentLength();

    // input stream to read file - with 8k buffer
    InputStream input = new BufferedInputStream(url.openStream(), 8192);

    // Output stream to write file
    OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

    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());
}

3 个答案:

答案 0 :(得分:1)

这是你想要的完整例子..

<强> AsyncOncImageActivity.java

public class AsyncOncImageActivity extends Activity {
/** Called when the activity is first created. */
ProgressBar pbHorizontal;
ImageView ivImage;
//Button btnIncrement;
String URL="http://appcolumn5.columnfivemedia.netdna-cdn.com/wp-content/uploads/2012/03/TakePart-Infographic_MarijuanaAttitudesandLegislation.png";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    /*** FIND ALL COMPONENT ***/
    ivImage = (ImageView) findViewById(R.id.ivImage);
    pbHorizontal=(ProgressBar) findViewById(R.id.pbHorizontal);
    //btnIncrement=(Button) findViewById(R.id.btnIncrement);

    /*** DOWNLOAD IMAG FROM URL AND READ FROM SD CARD***/
    new AsyncDemo(URL,pbHorizontal,ivImage).execute(this);
}

class AsyncDemo extends AsyncTask<Context, ProgressBar, Bitmap>
{
    String url;
    Boolean cancelTask=true;
    ProgressBar pbHorizontal;
    ImageView ivImage;
    AsyncDemo(String url,ProgressBar pbHorizontal,ImageView ivImage)
    {
        this.url = url;
        this.pbHorizontal=pbHorizontal;
        this.ivImage=ivImage;
    }

    @Override
    protected Bitmap doInBackground(Context... params) {
        // TODO Auto-generated method stub
        try {
            File root = Environment.getExternalStorageDirectory();
            URL u = new URL(url);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            FileOutputStream f = new FileOutputStream(new File(root, "c5.jpg"));

            InputStream in = c.getInputStream();
                // here u will get content length (Size of image)
            System.out.println("Content length"+c.getContentLength());
            //pbHorizontal.setMax(c.getContentLength());

            byte[] buffer = new byte[1024];
            int len1 = 0;
            /*** WRITTING IMAGE TO SD CARD **/
            while ((len1 = in.read(buffer)) > 0)// && cancelTask==true) 
            {
                f.write(buffer, 0, len1);
                System.out.println("current buf: "+len1);
                //pbHorizontal.incrementProgressBy(len1);
                pbHorizontal.setProgress(pbHorizontal.getProgress()+len1);
                //System.out.println("status Loop:"+this.getStatus());
            }
            f.close();// image stored in sd card


            /*** READING IMAGE FROM SD CARD ***/
            String imageInSD = "/sdcard/c5.jpg";
           // System.out.println("statusf inis:"+this.getStatus());
            Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);

            return bitmap;

        } catch (Exception e) {
            Log.d("Downloader", e.getMessage());
            return null;
        }
    }
    @Override
    protected void onPostExecute(Bitmap result )  
    {
        ivImage.setImageBitmap(result);
        pbHorizontal.setVisibility(ProgressBar.GONE);
    }
    protected void stopIt()
    {
        cancelTask=false;
    }
}

}

<强> main.xml中     

    <ImageView
        android:id="@+id/ivImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@drawable/ic_launcher" />



    <ProgressBar
        android:id="@+id/pbHorizontal"
        android:progress="0"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="64dp" />

</RelativeLayout>

答案 1 :(得分:1)

httpEntity.getContentLength()

答案 2 :(得分:0)

File root = Environment.getExternalStorageDirectory();
        URL u = new URL(url);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();

       // FileOutputStream f = new FileOutputStream(new File(root, "c5.jpg"));

        InputStream in = c.getInputStream();
            // here u will get content length (Size of image)
        System.out.println("Content length"+c.getContentLength());

此代码将为您提供图像的大小(LENGTH)尝试此