怎样实现在android实现带进度条的上传效果

怎样实现在android实现带进度条的上传效果,第1张

实现在android实现带进度条的上传效果效果如图:

用到以下两个类就可实现带进度条的文件上传:

1、CustomMultiPartEntity extends MultipartEntity,

2、HttpMultipartPost extends AsyncTask

代码如下:

import java.io.FilterOutputStream

import java.io.IOException

import java.io.OutputStream

import java.nio.charset.Charset

import org.apache.http.entity.mime.HttpMultipartMode

import org.apache.http.entity.mime.MultipartEntity

public class CustomMultipartEntity extends MultipartEntity {

  private final ProgressListener listener

  public CustomMultipartEntity(final ProgressListener listener) {

      super()

      this.listener = listener

  }

  public CustomMultipartEntity(final HttpMultipartMode mode, final ProgressListener listener)     {

      super(mode)

      this.listener = listener

  }

  public CustomMultipartEntity(HttpMultipartMode mode, final String boundary,

          final Charset charset, final ProgressListener listener) {

      super(mode, boundary, charset)

      this.listener = listener

  }

  @Override

  public void writeTo(final OutputStream outstream) throws IOException {

      super.writeTo(new CountingOutputStream(outstream, this.listener))

  }

  public static interface ProgressListener {

      void transferred(long num)

  }

  public static class CountingOutputStream extends FilterOutputStream {

      private final ProgressListener listener

      private long transferred

      public CountingOutputStream(final OutputStream out, final ProgressListener listener) {

          super(out)

          this.listener = listener

          this.transferred = 0

      }

      public void write(byte[] b, int off, int len) throws IOException {

          out.write(b, off, len)

          this.transferred += len

          this.listener.transferred(this.transferred)

      }

      public void write(int b) throws IOException {

          out.write(b)

          this.transferred++

          this.listener.transferred(this.transferred)

      }

  }

}

该类计算写入的字节数,我们需要在实现ProgressListener中的trasnfered()方法,更行进度条

public  class HttpMultipartPost extends AsyncTask<HttpResponse, Integer, TypeUploadImage>{

  ProgressDialogpd

  longtotalSize

  @Override

  protectedvoidonPreExecute(){

      pd= newProgressDialog(this)

      pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)

      pd.setMessage("Uploading Picture...")

      pd.setCancelable(false)

      pd.show()

  }

  @Override

  protectedTypeUploadImagedoInBackground(HttpResponse... arg0) {

      HttpClienthttpClient = newDefaultHttpClient()

      HttpContexthttpContext = newBasicHttpContext()

      HttpPosthttpPost = newHttpPost("http://herpderp.com/UploadImage.php")

      try{

          CustomMultipartEntitymultipartContent = newCustomMultipartEntity(

                  newProgressListener() {

                      @Override

                      public void transferred(longnum){

                          publishProgress((int) ((num / (float) totalSize) * 100))

                      }

                  })

          // We use FileBody to transfer an image

          multipartContent.addPart("uploaded_file", newFileBody(

                  newFile(m_userSelectedImagePath)))

          totalSize= multipartContent.getContentLength()

          // Send it

          httpPost.setEntity(multipartContent)

          HttpResponseresponse = httpClient.execute(httpPost, httpContext)

          String serverResponse = EntityUtils.toString(response.getEntity())

          ResponseFactoryrp = newResponseFactory(serverResponse)

          return(TypeImage) rp.getData()

      }

      catch(Exception e) {

          System.out.println(e)

      }

      returnnull

  }

  @Override

  protectedvoidonProgressUpdate(Integer... progress){

      pd.setProgress((int) (progress[0]))

  }

  @Override

  protectedvoidonPostExecute(TypeUploadImageui) {

      pd.dismiss()

  }

}

在 transferred()函数中调用publishProgress((int) ((num / (float) totalSize) * 100))

在onProgressUpdate()实现上传进度的更新 *** 作

可使用android自带的httpclient框架实现,附件中已经现成的示例代码,带上传进度。

1. GET 方式传递参数

//先将参数放入List,再对参数进行URL编码

List<BasicNameValuePair>params = new LinkedList<BasicNameValuePair>()

params.add(new BasicNameValuePair("param1", "数据"))    //增加参数1

params.add(new BasicNameValuePair("param2", "value2"))//增加参数2

String param = URLEncodedUtils.format(params, "UTF-8")//对参数编码

String baseUrl = "服务器接口完整URL"

HttpGet getMethod = new HttpGet(baseUrl + "?" + param)//将URL与参数拼接

HttpClient httpClient = new DefaultHttpClient()

try {

  HttpResponse response = httpClient.execute(getMethod)//发起GET请求

  Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode())//获取响应码

  Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"))//获取服务器响应内容

} catch (ClientProtocolException e) {

  e.printStackTrace()

} catch (IOException e) {

  e.printStackTrace()

}

2. POST方式 方式传递参数

//和GET方式一样,先将参数放入List

params = new LinkedList<BasicNameValuePair>()

params.add(new BasicNameValuePair("param1", "Post方法"))//增加参数1

params.add(new BasicNameValuePair("param2", "第二个参数"))//增加参数2

try {

  HttpPost postMethod = new HttpPost(baseUrl)//创建一个post请求

  postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8"))//将参数填入POST Entity中

  HttpResponse response = httpClient.execute(postMethod)//执行POST方法

  Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode())//获取响应码

  Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"))//获取响应内容

} catch (UnsupportedEncodingException e) {

  e.printStackTrace()

} catch (ClientProtocolException e) {

  e.printStackTrace()

} catch (IOException e) {

  e.printStackTrace()

}

手上项目需要实现选择多个视频后在上传腾讯云,由于视频较大大,所以选择Service来进行上传任务,配合Notification显示进度。

打开server直接发送一个Notification并拿到RemoteViews ;

这里要兼容下8.0设置好渠道id;

下面开始上传

最后效果如图,layout可以自己定义

如果无法显示通知那应该安装时默认设置了关闭通知,需要进入通知管理打开


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/8107341.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-13
下一篇 2023-04-13

发表评论

登录后才能评论

评论列表(0条)

保存