1

是否可以在以下代码中合并水平进度条?我在想 os AsyncTask 但后来我意识到,我不能将整数值传递给 doInBackground() 中的 ProgressUpdate() 方法。请帮忙!

public void sendFileDOS() throws FileNotFoundException {
    runOnUiThread( new Runnable() {
          @Override
          public void run() {
              registerLog("Sending. . . Please wait. . .");
          }
        });
    final long startTime = System.currentTimeMillis();
    final File myFile= new File(filePath); //sdcard/DCIM.JPG
    byte[] mybytearray = new byte[(int) myFile.length()];
    FileInputStream fis = new FileInputStream(myFile);  
    BufferedInputStream bis = new BufferedInputStream(fis);
    DataInputStream dis = new DataInputStream(bis);
    try {
        dis.readFully(mybytearray, 0, mybytearray.length);
        OutputStream os = socket.getOutputStream();
        //Sending file name and file size to the server  
        DataOutputStream dos = new DataOutputStream(os);     
        dos.writeUTF(myFile.getName());     
        dos.writeLong(mybytearray.length);     
        dos.write(mybytearray, 0, mybytearray.length);     
        dos.flush();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    runOnUiThread( new Runnable() {
          @Override
          public void run() {
              long estimatedTime = (System.currentTimeMillis() - startTime)/1000;
              registerLog("File successfully sent");
              registerLog("File size: "+myFile.length()/1000+" KBytes");
              registerLog("Elapsed time: "+estimatedTime+" sec. (approx)");
              registerLog("Server stopped. Please restart for another session.");
              final Button startServerButton=(Button)findViewById(R.id.button1);
              startServerButton.setText("Restart file server");
          }
        });
}
4

3 回答 3

4

对于那些面临类似问题的人,这里是使用数据输出流进行文件传输的工作方法。主要思想是将文件分成多个块(我已分成 100 个块)并在 while 循环中写入 DOS。使用循环计数器更新进度条。确保在主 UI 线程中更新进度条,否则应用程序会崩溃。代码如下:

public void sendFileDOS() throws FileNotFoundException {
    runOnUiThread( new Runnable() {
          @Override
          public void run() {
              registerLog("Sending. . . Please wait. . .");
          }
        });
    final long startTime = System.currentTimeMillis();
    final File myFile= new File(filePath); //sdcard/DCIM.JPG
    byte[] mybytearray = new byte[(int) myFile.length()];
    FileInputStream fis = new FileInputStream(myFile);  
    BufferedInputStream bis = new BufferedInputStream(fis);
    DataInputStream dis = new DataInputStream(bis);
    try {
        dis.readFully(mybytearray, 0, mybytearray.length);
        OutputStream os = socket.getOutputStream();
        //Sending file name and file size to the server  
        DataOutputStream dos = new DataOutputStream(os);     
        dos.writeUTF(myFile.getName());     
        dos.writeLong(mybytearray.length);     
        int i = 0;
        final ProgressBar myProgBar=(ProgressBar)findViewById(R.id.progress_bar);
        while (i<100) {
            dos.write(mybytearray, i*(mybytearray.length/100), mybytearray.length/100);
            final int c=i;
            runOnUiThread( new Runnable() {
                  @Override
                  public void run() {
                      registerLog("Completed: "+c+"%");
                      myProgBar.setProgress(c);
                  }
                });
            i++;
        }    
        dos.flush();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    runOnUiThread( new Runnable() {
          @Override
          public void run() {
              long estimatedTime = (System.currentTimeMillis() - startTime)/1000;
              registerLog("File successfully sent");
              registerLog("File size: "+myFile.length()/1000+" KBytes");
              registerLog("Elapsed time: "+estimatedTime+" sec. (approx)");
              registerLog("Server stopped. Please restart for another session.");
              final Button startServerButton=(Button)findViewById(R.id.button1);
              startServerButton.setText("Restart file server");
          }
        });
}

干杯! :)

于 2013-06-24T22:07:33.917 回答
1

您可以使用 AsyncTask 获得这样的进度条:

public abstract class BaseTask extends AsyncTask<String, Integer, String> 
{   
    private ProgressBar    m_progressBar;

    protected BaseTask(ProgressBar p)
    {
        m_progressBar = p;
    }

    @Override
    protected void onPreExecute()
    {   
        if (m_progressBar != null)
        {
            m_progressBar.setProgress(0);
        }
    }

    @Override
    protected void onPostExecute(String result)
    {   
        if (m_progressBar != null)
            m_progressBar.setVisibility(ProgressBar.GONE);
    }

    public void OnProgress(int prog)
    {
        if (m_progressBar != null)
        {
            m_progressBar.setProgress(prog);
        }
    }
}

要在 xml 中添加进度条:

<ProgressBar
 android:id="@+id/progressBar"
 style="?android:attr/progressBarStyleHorizontal"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_margin="10dp" />

在代码中初始化进度条:

ProgressBar p = (ProgressBar)findViewById(R.id.progressBar);
p.setVisibility(ProgressBar.VISIBLE);
p.setMax(100);
于 2013-06-24T16:04:51.603 回答
0

我无法将整数值传递给 doInBackground() 中的 ProgressUpdate() 方法

是的你可以 !

publishProgress与内部所需的参数一起使用doInBackground以触发onProgressUpdate

final class MyTask extends AsyncTask<Void, Integer, Void> {

    private final ProgressBar progress;

    public MyTask(final ProgressBar progress) {
        this.progress = progress;
    }

    @Override
    protected void onPreExecute() {
        progress.setMax(100);
    }

    @SuppressWarnings("unchecked")
    @Override
    protected Void doInBackground(final Void... params) {
        ...
        int progress_val = // What ever you want
        publishProgress(progress_val);  // Here we trigger 'onProgressUpdate' 
                                        // with the updated integer as parameter
        return null;
    }

    @Override
    protected void onProgressUpdate(final Integer... values) {
        progress.incrementProgressBy(values[0]);  // Here we update the bar
    }

    @Override
    protected void onPostExecute(final Void result) {
        parent.finish();
    }
}

编辑 :

分块写的建议:

int i = 0;
int offset = 0;
int buflen = mybytearray.length/100;
while (i<100) {
    dos.write(mybytearray, offset, buflen);
    offset += buflen;
    i++;
}
dos.write(mybytearray, offset, mybytearray.length%100);
于 2013-06-24T15:49:16.267 回答