在While循环中设置TextView以进行打印时间

时间:2016-11-10 05:25:26

标签: java android time android-asynctask

protected String doInBackground(String... Url) {
  try {
      URL url = new URL(Url[0]);
      URLConnection connection = url.openConnection();
      connection.connect();

      //Detect File Length
      int fileLength = connection.getContentLength();

      //Locate Storage Location
      String filePath = Environment.getExternalStorageDirectory().getPath();

      //Downloading File
      final InputStream input = new BufferedInputStream(url.openStream());

      //Save the Download File
      OutputStream output = new FileOutputStream(filePath + "/" + "Ardu_Vid.mp4");

      final byte data[] = new byte[fileLength];
      long total = 0;
      int count;

      long Start_Timee = System.currentTimeMillis();
      while ((count = input.read(data)) != -1) {

          total += count;
          output.write(data, 0, count);

          //publish the progress
          publishProgress((int) (total * 100 / fileLength));

          Long End_Timee = System.currentTimeMillis();
          Log.e("Time_End", "" + End_Timee);

          final long timeDiff = End_Timee - Start_Timee;

      /************ Get Duration of Downloading ***************/

          Long allTimeForDownloading = (timeDiff * fileLength / total);
          Long remainingTime = allTimeForDownloading - timeDiff;
          int seconds = (int) (remainingTime / 1000) % 60 ;
          int minutes = (int) ((remainingTime / (1000*60)) % 60);
          Log.e("elapse",""+minutes+":"+seconds);
  //Problem is here
          textView.setText(""+minutes +" : "+ seconds);

      }// end while

我的编码工作正常,但是当我为下载文件的打印剩余时间添加textView.setText时,它的工作不正常问题是我得到了剩余时间抛出循环但我的文本视图未设置时间我在日志中打印时间时动态循环我得到了准确的结果。请帮帮我。

1 个答案:

答案 0 :(得分:0)

您正在尝试从运行AsyncTask的后台(工作人员)主题与Android UI进行交互。这在Android中是不允许的,因为UI框架不是线程安全的。 very well documented你应该只从Android为你的应用程序创建的主(UI)线程触摸UI:

  

此外,Andoid UI工具包不是线程安全的。因此,您不能从工作线程操纵UI - 您必须从UI线程对用户界面进行所有操作。

事实上,这是AsyncTask的整个目的及其结构的方式。 doInBackground在后​​台(工作者)线程上运行,并在UI线程上调用回调方法(例如onProgressUpdate),以便您可以轻松安全地与UI交互以响应进度和任务的结果。

您似乎已经正确地为百分比进度执行了此操作,您可以在其中调用publishProgress。我不知道你在onProgressUpdate中对这些数据做了什么,但我猜你是在UI中显示它?

基于此,一个简单易用(尽管不一定是最好的)解决方案是利用事实publishProgressonProgressUpdate具有varargs方法参数并且不仅返回百分比进度但minutesseconds同一次调用publishProgressonProgressUpdate。然后,在TextView中,只需解压缩额外的值,然后在那里更新var numFormat = new Intl.NumberFormat("en-US", { style: 'currency', currency: 'USD' });

相关问题