android - 如何取消像whatsapp这样的图片和视频上传

标签 android android-progressbar androidhttpclient multipartentity httpentity

我正在使用 multipart 将图像和视频上传到 php 服务器。 我希望能够在用户按下 whatsapp 之类的按钮时取消上传。

进度显示正确,但我只想取消点击上传,但我不知道如何操作。

这是我当前的源代码:

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;

}

最佳答案

调用asyncTask的cancel方法取消上传/下载的执行。

关于android - 如何取消像whatsapp这样的图片和视频上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31315448/

相关文章:

android - AsyncTask onPreExecute 进度对话框

android - 带分隔线的进度条

android - 如何在android中为progressBar设置流畅的动画

android - 检查 Android 中的工作互联网连接

Xamarin Native Android HttpClient,它位于哪里?

java - Android 对服务器进行 PATCH/PUT

java - 是否可以为工具栏设置多行标题?

java - 如何在 Service 类的 onCreate() 方法中使用 findViewById?

java - ProgressBar 在 RecyclerView Adapter 中不刷新

安卓随机资源