代码之家  ›  专栏  ›  技术社区  ›  dev_android

Android显示RESTful API的进度百分比

  •  0
  • dev_android  · 技术社区  · 9 年前

    我试图使用以下代码调用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 回复  |  直到 9 年前
        1
  •  2
  •   Abdul Aleem    9 年前

    试试这段代码,我已经在我的一个应用程序中实现了这段代码!你可以知道如何显示百分比!这段代码实际上是从服务器下载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]);
        }
    }
    
        2
  •  1
  •   Community CDub    8 年前

    正如这个问题所述,你通常不会提前知道河流的大小 https://stackoverflow.com/a/1119346/2122552 声明的答案还链接到获取文件大小的api。但是对于RESTful API,您通常不知道Inputstream的确切大小。

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

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