Android 显示 RESTful API 的百分比进度

Android show the percentage progress of RESTful API

我正在尝试使用以下代码调用 Restful api。现在我想显示进度(下载的百分比)。有可能吗?如果需要,需要对代码进行哪些更改?

    BufferedReader reader=null;
    try{
         URL mUrl = new URL("http://dev.amazaws.com/formservice/rest/v1/registrationreports/registrationsbyproduct/132866/");

         URLConnection conn = url.openConnection();
         conn.setDoOutput(true);
         OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
         writer.write( data );
         writer.flush();
         reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         StringBuilder sb = new StringBuilder();
         String line = null;

         while((line = reader.readLine()) != null)
         {
                    sb.append(line);
         }

         String res = sb.toString();
 }catch(Exception ex){

 }finally{
     try{
       reader.close();
     }catch(Exception ex) {}
}

如这个问题所述,您通常不会提前知道流的大小 陈述的答案还链接到 api 以获取文件大小。但是对于 RESTful API 你通常不知道输入流的确切大小。

但是,但是,如果您知道大小,则可以将其分解为使用 100 作为 100%,并将进度计算为 (downloadedBytes/fileSizeInBytes * 100)。否则只需使用不确定的 ProgressBar。

当你不知道答案的大小时,你可以检查大小写并使进度条不确定,否则计算进度并更新它,如官方文档所示

试试这个代码,我已经在我的一个应用程序中实现了这个代码!您可以了解如何显示百分比!好吧这段代码实际上是从服务器下载 JSON 并将其保存在移动设备上。

public class LoginActivity extends Activity {
private ProgressDialog prgDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_layout);
}

//  Button Click function, on which you want to make restApi call
public void buttonClicked(View view){
    new PrefetchData().execute();
}
 private class PrefetchData extends AsyncTask<Void, Integer, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // before making http calls
        prgDialog = new ProgressDialog(LoginActivity.this);
        prgDialog.setMessage("Downloading Data. Please wait...");
        prgDialog.setIndeterminate(false);
        prgDialog.setMax(100);
        prgDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        prgDialog.setCancelable(false);
        prgDialog.show();
    }
  @Override
    protected Void doInBackground(Void... arg0) {

        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL("http://xyz/testJSON");
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
             //  Show ERROR
            }

            int fileLength = connection.getContentLength();


            input = connection.getInputStream();


            String extPath = Environment.getExternalStorageDirectory() + "/"        + FILE_PATH;
            //     Environment.
            File file = new File(extPath);
            if(!file.exists()){
                file.createNewFile();
            }
            output = new FileOutputStream(extPath);


            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                if (fileLength > 0){
                // only if total length is known
                // publishing the progress....
                    publishProgress((int) (total * 100 / fileLength));
                }

                output.write(data, 0, count);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }

            if (connection != null)
                connection.disconnect();
        }
        return null;
    }


    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // After completing http call
        // will close this activity and lauch main activity
        Intent i = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(i);

        // close this activity
        finish();
    }

    //Update the progress
    @Override
    protected void onProgressUpdate(Integer... values)
    {
        prgDialog.setProgress(values[0]);
    }
}