【问题标题】:Horizontal Progress Bar Not Working in Asynctask Android For Download file?水平进度条不适用于 Asynctask Android 下载文件?
【发布时间】:2014-07-24 17:50:27
【问题描述】:

我正在尝试使用Asynctask 显示水平进度条,但它不适合我。它不是显示百分比进度量。

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

布局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() 
                {

                }

            });
     }


}

【问题讨论】:

  • 永远不要更新doInBackground()中的任何用户界面。

标签: android android-asynctask progress-bar


【解决方案1】:

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

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

并通过像这样调用publishProgress(...) 在您的doInBackground(..) 中使用它。

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

【讨论】:

  • 但我没用过progressdiaog 我用过progressbar
  • @AndroidTech 更改进度条
  • @AndroidTech 为什么在TextView 中显示进度?实现Progress dialog并将样式设置为STYLE_HORIZONTAL它会显示进度
  • 我想创建定制设计,因为它是需要的
  • @AndroidTech 如果您真的要这样做,那么我还有另一种方法。创建一个单独的Thread 并在其上执行此操作并创建一个Handler,它将更新您的ProressBar 并在您的TextView 中显示进度。
【解决方案2】:

您不能从后台线程更新视图,只有 UI 线程可以触摸视图。实际上,您没有异常是很奇怪的。为了从后台线程更新视图,您可以使用Activity.runOnUiThread 方法或Handler 类。但请记住,应在 UI 线程中创建 Handler 以便使用它

【讨论】:

    【解决方案3】:

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

    在这里你必须更新你的 ProgressBar

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

    请参阅AsyncTask 文档中的示例:

     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)

    【讨论】:

      猜你喜欢
      • 2014-03-04
      • 1970-01-01
      • 2012-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      • 2012-01-01
      • 2012-06-26
      相关资源
      最近更新 更多