【问题标题】:Android Download With Progress BarAndroid 下载带进度条
【发布时间】:2012-04-06 15:23:21
【问题描述】:

我会怎么做才能得到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());
}

【问题讨论】:

    标签: android android-progressbar


    【解决方案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;
        }
    }
    

    }

    ma​​in.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>
    

    【讨论】:

    • 我想你误解了我的问题,请再读一遍。
    • 我的代码使用HttpGet,如上所示,我正在尝试找到一种在我的代码中使用InputStream OutputStream getContentLength 的方法(使用HttpGet)
    • int lenghtOfFile = conection.getContentLength();它不工作吗
    • 使用显示百分比的进度条的示例代码,我正在尝试对我的代码使用相同的概念,即原始问题中发布的 HttpGet - 我希望它清楚,如果不是那么让我知道。
    • 我没有使用连接,你看到我的代码了吗?,不要看示例代码
    【解决方案2】:

    httpEntity.getContentLength()?

    【讨论】:

      【解决方案3】:
      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());
      

      此代码将为您提供图像的大小(长度)试试这个

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-08
        • 1970-01-01
        • 2013-11-21
        相关资源
        最近更新 更多