3

このファイル アップロード機能の進捗率を計算できません。私はそれをたくさんグーグルで検索しましたが、解決策が見つかりませんでした

これが私のコードです:

protected void onProgressUpdate(Integer... progress) {
    super.onProgressUpdate(progress);

    notification.contentView.setProgressBar(R.id.progressBar, 10, progress[0], false);
    contentView.setTextViewText(R.id.text, "changed");
    mNotificationManager.notify(NOTIFICATION_ID, notification);
}

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

    String upLoadServerUri = upurl;
    String fileName = urls[0];
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 100 * 1024 * 1024;
    File sourceFile = new File(fileName);
    int sentBytes = 0;
    long fileSize = sourceFile.length();

     try {
            FileInputStream fileInputStream = new FileInputStream(new File(urls[0]));

            URL url = new URL(upurl);
            connection = (HttpURLConnection) url.openConnection();

            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            // Enable POST method
            connection.setRequestMethod("POST");

            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type",     "multipart/form-data;boundary="+boundary);

            outputStream = new DataOutputStream(     connection.getOutputStream() );
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"file[]\";filename=\""+ fileName + "\"" + lineEnd);
            outputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            Log.v("Size",bytesAvailable+"");

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // Read file
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                // Update progress dialog
                sentBytes += bytesRead;
                publishProgress((int)(sentBytes * 100 / fileSize));

                outputStream.write(buffer, 0, bufferSize);

                bytesAvailable = fileInputStream.available();
                Log.v("Available",bytesAvailable+"");

                bufferSize = Math.min(bytesAvailable,     maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0,      bufferSize);
            }

            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            Scanner s = new Scanner(connection.getInputStream());
            s.useDelimiter("\\Z");
            final String response = s.next();

            // Responses from the server (code and message)
            int serverResponseCode       = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            if(serverResponseCode == 200) {
                 runOnUiThread(new Runnable() {
                      public void run() {

                         Toast.makeText(BabupMain.this, "server say :" + response , Toast.LENGTH_SHORT).show();
                         Toast.makeText(BabupMain.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                      }
                  });
             }

            fileInputStream.close();
            outputStream.flush();
            outputStream.close();

        } catch (MalformedURLException ex) {

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(BabupMain.this, "Error 1 ", Toast.LENGTH_SHORT).show();
                }
            });

        } catch (final Exception e) {

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(BabupMain.this, "Error 2 "+ e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        }

        //publishProgress();

        return null;
}
4

3 に答える 3

1

一概には言えませんが、変更を検討してください

publishProgress((int)(sentBytes * 100 / fileSize))

double progress = (double)sentBytes / fileSize;
publishProgress((int)progress);

編集

私はこれを変更します:

bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0)
{

      // Update progress dialog
    sentBytes += bytesRead;
    publishProgress((int)(sentBytes * 100 / fileSize));

    outputStream.write(buffer, 0, bufferSize);

    bytesAvailable = fileInputStream.available();
    Log.v("Available",bytesAvailable+"");



    bufferSize = Math.min(bytesAvailable,     maxBufferSize);
    bytesRead = fileInputStream.read(buffer, 0,      bufferSize);
}

バッファ = 新しいバイト [maxBufferSize];

while (true)
{
    int bytesToRead = Math.min(maxBufferSize, fileInputStream.available());

    // Break if complete
    if(bytesToRead == 0){ break; }

    // Read bytes
    bytesRead = fileInputStream.read(buffer, 0, bytesToRead);

    // Write bytes
    outputStream.write(buffer, 0, bytesRead);

    // Update progress dialog
    sentBytes += bytesRead;

    // Publish progress
    double progress = (double)sentBytes / fileSize;
    publishProgress((int)progress);
}

これに問題がある場合は、FileInputStream.available()アプローチを放棄し、 から合計バイト数を取得しFile.length()てループから抜け出しますbytesRead >= File.length()

于 2013-04-01T17:30:27.720 に答える
0

ここにシンプルで素敵な解決策があります: https://developer.android.com/reference/java/net/HttpURLConnection.htmlセクションの「コンテンツの投稿」:

追加:

connection.setChunkedStreamingMode(0);

すぐ後:

connection.setDoOutput(true);
于 2016-09-24T03:40:48.453 に答える
0

ざっと見ただけで…

  1. sentBytes * 100 / ファイルサイズ

    int sentBytes = 0;
    長いファイルサイズ = sourceFile.length();

    int と long で計算すると、小数点以下が切り替わることに注意してください。たぶんダブルにキャストします。

  2. 2番目はコードが見つからないために表示されませんが、コメントはそれを求めています

    しかし、通知がスティッキーになり、電話がフリーズします

    バックグラウンド スレッド (doInBackground()) で publishProgress() を使用しています。バックグラウンド スレッドで GUI に触れないでください。

    Handler() を使用して、GUI スレッドで使用される Runnable を投稿できます

于 2016-06-10T12:13:11.637 に答える