1

I have an Android App and I want to download a big file.

REST API implementation is made with AndroidAnnotations. I need to show a progressbar with the download of a big file using this REST Client (made by AndroidAnnotations).

How I to do that?

Regards

Mou
  • 2,027
  • 1
  • 18
  • 29

5 Answers5

2

Hello Its to late for answering this question but this will be helpful who are still finding ans with Android-annotation

You can check your image progress by little bit manipulation of code and here is what i have created my

Custom converter Class:-

public class CustomConverter extends FormHttpMessageConverter {

OnProgressListener mOnProgressListener;

public CustomConverter() {
    super();

    List<HttpMessageConverter<?>> partConverters = new ArrayList<HttpMessageConverter<?>>();
    partConverters.add(new ByteArrayHttpMessageConverter());
    StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
    stringHttpMessageConverter.setWriteAcceptCharset(false);
    partConverters.add(stringHttpMessageConverter);
    partConverters.add(new ProgressResourceHttpMessageConverter());
    setPartConverters(partConverters);
}

// public ProgressFormHttpMessageConverter setOnProgressListener(OnProgressListener listener) { // mOnProgressListener = listener; // return this; // }

class ProgressResourceHttpMessageConverter extends ResourceHttpMessageConverter {

    @Override
    protected void writeInternal(Resource resource, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        InputStream inputStream = resource.getInputStream();
        OutputStream outputStream = outputMessage.getBody();

        byte[] buffer = new byte[2048];
        long contentLength = resource.contentLength();
        int byteCount = 0;
        int bytesRead = -1;
        Log.d("<3 <3 <3", "called");
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
            byteCount += bytesRead;
            Log.d("<3 <3 <3 ** ", "progress" + String.valueOf((byteCount * 100) / contentLength));
            if(mOnProgressListener != null) {
                mOnProgressListener.onProgress(resource, byteCount, (int) contentLength);
            }
        }
        outputStream.flush();
    }
}

public interface OnProgressListener {
    void onProgress(Resource resource, int downloaded, int downloadSize);
}
}

--> you can check your progress with log :)

Code Usage

-> Your rest class will be as follow:-

@Rest(rootUrl = CommonUtils.BASE_URL, converters = {ByteArrayHttpMessageConverter.class,
    CustomConverter.class, StringHttpMessageConverter.class})

public interface CustomRest extends RestClientErrorHandling {


@Post(pUrlSignUp)
String _SignUp(MultiValueMap<String, Object> multiValueMap);

}
Hardy
  • 2,576
  • 1
  • 23
  • 45
0

Of course, you will have to use AsyncTask for downloading purpose:

You can use its methods onPreExecute and onPostExecute for showing and dismissing the ProgressDialog respectively.

Example:

public class DownloadTask extends AsyncTask<String, Integer, String>
{
    ProgressDialog pDialog;
    Activity activity;  //pass your activity reference while initialize this.

    public DownloadTask (Activity activity){
        this.activity = activity;
    }

    @Override
    protected void onPreExecute()
    {
        pDialog = new ProgressDialog(activity);
        pDialog.setMessage("Downloading file...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) 
    {
        //download file's code here
    }

    @Override
    protected void onPostExecute(String result) 
    {
        pDialog.dismiss();
    }
}

Hope this helps.

MysticMagicϡ
  • 28,593
  • 16
  • 73
  • 124
0
> use AsyncTask method "on progressupdate " to show progress
public class download extends Activity {

public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    startBtn = (Button)findViewById(R.id.startBtn);
    startBtn.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {
            startDownload();
        }
    });
}

private void startDownload() {
    String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
    new DownloadFileAsync().execute(url);
}
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_DOWNLOAD_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Downloading file..");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
        return mProgressDialog;
    default:
        return null;
    }
}

class DownloadFileAsync extends AsyncTask {

@Override
protected void onPreExecute() {
    super.onPreExecute();
    showDialog(DIALOG_DOWNLOAD_PROGRESS);
}

@Override
protected String doInBackground(String... aurl) {
    int count;

try {

URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();

int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg");

byte data[] = new byte[1024];

long total = 0;

    while ((count = input.read(data)) != -1) {
        total += count;
        publishProgress(""+(int)((total*100)/lenghtOfFile));
        output.write(data, 0, count);
    }

    output.flush();
    output.close();
    input.close();
} catch (Exception e) {}
return null;

}
protected void onProgressUpdate(String... progress) {
     Log.d("ANDRO_ASYNC",progress[0]);
     mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}

@Override
protected void onPostExecute(String unused) {
    dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}

} }

Sukhbir
  • 1,410
  • 14
  • 33
0

With AndroidAnnotations, you can use background threads and publishing progress easily:

@EActivity
public class MyActivity extends Activity {

  public void onCreate(Bundle icicle) {
    super.onCreate(icicle)
    doSomeStuffInBackground();
  }

  @Background
  void doSomeStuffInBackground() { // will run on a background thread
    publishProgress(0);
    // Do some stuff
    publishProgress(10);
    // Do some stuff
    publishProgress(100);
  }

  @UiThread
  void publishProgress(int progress) { // will run on the UI thread
    // Update progress views
  }

}

Now you can only have to figure out how you can get progress events. This answer can give a great inspiration. Unfortunetaly AFAIK there is no built-in callback for that in Spring Android Rest Template.

Community
  • 1
  • 1
WonderCsabo
  • 11,947
  • 13
  • 63
  • 105
0

I was looking to solve this same problem, its being two months now. Finally found a good example, I cant believe everybody copy paste the same in AndroidAnnotations docs, if that were enough, we wouldnt be here seeking for help.

Here is the link where you can see the example

I made some modifications my self, for the moment its working with some toasts, but I hope to comeback with an actual loading animation to share:

    /*This background handles my main thread in UI and the progress publish*/
        @Background
        void thisGETJSON() {
            publishProgress(0);
            publishProgress(50);
            publishProgress(100);
            showJSONInUI();
        }

     /*Here the progress is published and the main UI thread is also called*/
        @UiThread
        void publishProgress(int progress) {

            if (progress == 0) {
                Toast toast = Toast.makeText(getApplicationContext(), "Just a sec please", Toast.LENGTH_SHORT);
                toast.show();
            } else if (progress == 50) {
                Toast toast = Toast.makeText(getApplicationContext(), "Loading", Toast.LENGTH_SHORT);
                toast.show();
            } else if (progress == 100) {
                Toast toast = Toast.makeText(getApplicationContext(), "Thanks for waiting", Toast.LENGTH_SHORT);
                toast.show();
            }

      /*This is the main UI thread here I do cool stuff with the JSON objects*/
       @UiThread
       Void showJSONInUI(); {
       //Here I do something with the objects in the JSON
       }
cutiko
  • 9,887
  • 3
  • 45
  • 59