androidandroid-progressbarandroidhttpclientmultipartentityhttpentity

How to cancel image and video upload like whatsapp


I am uploading an image and video on to a php server, using multipart. I want to be able to cancel the upload when user presses button like whatsapp.

The progress is shown correctly but I just want to cancel upload on click but I don't know how.

Here is my current source code:

private String uploadFile() {
    String responseString = null;
    int count;

       HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost(serviceurl+"conversations.php");

    try {
        MultipartEntityBuilder entity = MultipartEntityBuilder.create();        


        File sourceFile = new File(imgstring);
        /* example for setting a HttpMultipartMode */
        entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        if(Integer.parseInt(msgtype)==3)
        {

            entity.addPart("thumb", new FileBody(videothumb));
        }



        // Progress listener - updates task's progress

        MyHttpEntity.ProgressListener progressListener =
                new MyHttpEntity.ProgressListener() {
                    @Override
                    public void transferred(float progress) {
                       publishProgress((int) progress);
                       probar.setProgress((int) progress);


                    }
                };

        // Adding file data to http body
        entity.addPart("file", new FileBody(sourceFile));

        // Extra parameters if you want to pass to server
                entity.addTextBody("from_user",(prefid.getString("userid", null)),ContentType.TEXT_PLAIN);
        entity.addTextBody("to_user",userid,ContentType.TEXT_PLAIN);
        entity.addTextBody("message_type", msgtype,ContentType.TEXT_PLAIN); 

        httppost.setEntity(new MyHttpEntity(entity.build(),
                progressListener));

        // Making server call
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity r_entity = response.getEntity();

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {

            responseString = EntityUtils.toString(r_entity);
        } else {
            responseString = "Error occurred! Http Status Code: "
                    + statusCode;
        }
        // input.close();   
    } catch (ClientProtocolException e) {
        responseString = e.toString();
    } catch (IOException e) {
        responseString = e.toString();
    }

    return responseString;

}

Solution

  • Call cancel method of asynTask to cancel the execution of upload/download.