水平进度条不适用于Asynctask Android下载文件?

时间:2014-06-04 07:18:07

标签: android android-asynctask progress-bar

我正在尝试使用Asynctask显示水平进度条,但它对我不起作用。它不显示进度百分比。

这里我把我的xml和活动文件以及屏幕截图文件。

enter image description here

  

layout xml

<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android" 
        android:id="@+id/progresslayout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >

        <ImageView
            android:id="@+id/imagepeakmedia"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:src="@drawable/peakmedialogo" 
            android:layout_marginTop="100sp"
             />



        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/imagepeakmedia"
            android:layout_centerHorizontal="true"
            android:textSize="25sp"
           android:text="" />

        <TextView
            android:id="@+id/textpercentage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/imagepeakmedia"
            android:layout_toRightOf="@+id/text"
            android:layout_centerHorizontal="true"
            android:textSize="25sp"
            android:layout_marginLeft="5sp"
            android:text="%" />

        <ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/text"
            style="?android:attr/progressBarStyleHorizontal"

             />

    </RelativeLayout>
  

TestActivity.java

public class TestActivity extends Activity {


    ProgressDialog progressdialog;

    RelativeLayout progresslayout;
    ProgressBar progressbar;
    TextView textprogressbar;
    TextView textpercentage;
    TextView textdownload;

    boolean progress=true;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_progress);

            progressbar=(ProgressBar)findViewById(R.id.progressBar);
            textprogressbar=(TextView)findViewById(R.id.text);
            textpercentage=(TextView)findViewById(R.id.textpercentage);
            textdownload=(TextView)findViewById(R.id.textdownload);

             new FirstDownloadFileFromURL().execute("http://pr83.webofficeserver.info/img/thumbnails/video/iPhone5.mp4");

    }

    public class FirstDownloadFileFromURL extends AsyncTask<String, String, String> 
    {

        @SuppressWarnings("deprecation")
        @Override
        protected void onPreExecute() 
        {
            // some work
        }


        @Override
        protected String doInBackground(String... f_url) 
        {

            try 
            {   

                BufferedOutputStream out = null;

                String originalurl=f_url[0];
                Uri cu = Uri.parse(originalurl);
                File f2= new File("" + cu);
                String  filename=f2.getName();

                Log.i("DownloadFile", "DownloadURL:" +originalurl.replaceAll(" ", "%20"));
                Log.i("DownloadFile", "filename: " + filename);

                String root = Environment.getExternalStorageDirectory().getAbsolutePath();
                new File(root + "/montorwerbung").mkdirs();

                File SmartAR = new File(root + "/montorwerbung", "");
                SmartAR.mkdirs();
                File outputFile = new File(SmartAR, filename);
                FileOutputStream fos = new FileOutputStream(outputFile);
                String url1 = originalurl;
                HttpURLConnection conn = (HttpURLConnection) new URL(url1)
                .openConnection();
                conn.setDoInput(true);
                conn.connect();
                int lenghtOfFile = conn.getContentLength();
                final InputStream in = new BufferedInputStream(conn.getInputStream(), 1024); // buffer size
                // 1KB
                out = new BufferedOutputStream(fos, 1024);
                int b;
                int a=0;
                long total = 0;
                while ((b = in.read()) != -1) 
                {   
                    total += b;
                            publishProgress(""+(int)((total*100)/lenghtOfFile));

                        out.write(b);
                }
                out.close();
                conn.disconnect();

            } catch (final MalformedURLException e) {
                showError("Error : MalformedURLException " + e);        
                e.printStackTrace();
            } catch (final IOException e) {
                showError("Error : IOException " + e);          
                e.printStackTrace();
            }
            catch (final Exception e) {
                showError("Error : Please Check Your Wifi connection " + e);
            }       
            return null;
        }


         @Override
    protected void onProgressUpdate(String... progress) {
         Log.d("ANDRO_ASYNC",progress[0]);
         progressbar.setProgress(Integer.parseInt(progress[0]));
    }

        @SuppressWarnings("deprecation")
        @Override
        protected void onPostExecute(String file_url) 
        {

            // some work

        }
    }  


    public void showError(final String err)
     {
            runOnUiThread(new Runnable() 
            {
                public void run() 
                {

                }

            });
     }


}

3 个答案:

答案 0 :(得分:5)

您需要为此实施onProgressUpdate(....)

    @Override
    protected void onProgressUpdate(String... progress) {
         Log.d("ANDRO_ASYNC",progress[0]);
         mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

并在doInBackground(..)中通过调用publishProgress(...)来使用它。

while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}

答案 1 :(得分:0)

您无法从后台线程更新视图,只有UI线程可以触摸视图。实际上你没有得到例外是很奇怪的。要从后台线程更新视图,您可以使用Activity.runOnUiThread方法或Handler类。但请记住,应该在UI线程中创建Handler以便使用它

答案 2 :(得分:0)

这不是自动的,AsyncTask有一个onProgressUpdate方法你必须实现

您需要更新ProgressBar

然后你必须调用publishProgress来调用该方法,然后你就完成了

请参阅AsyncTask doc:

中的示例
 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }
}

在这里,他们使用他们的setProgressPercent()更新他们想要的内容(所以你的ProgressBar)