Android显示RESTful API的百分比进度

时间:2015-09-03 12:04:08

标签: android rest bufferedreader progress outputstream

我正在尝试使用以下代码调用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) {}
}

2 个答案:

答案 0 :(得分:2)

试试这段代码,我在我的一个应用程序中实现了这段代码!您可以了解如何显示百分比!以及这段代码实际上是从服务器下载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]);
    }
}

答案 1 :(得分:1)

正如此问题中所述,您通常不会提前知道流的大小https://stackoverflow.com/a/1119346/2122552 所述答案还链接到api以获取Filesizes。但是使用RESTful API,您通常不知道Inputstream的确切大小。

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

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