Android file Upload sample with progress bar (using Asynctask asynchronous Task) _android

Source: Internet
Author: User

The recent project to do with a progress bar upload file function, learn the asynctask, use up more convenient, will be a few methods to achieve on the line, and also made a very simple demo, I hope to be helpful, in the program to set the file path and server IP can be.

Demo Run screenshot:

Asynctask is an abstract class, and subclasses must implement abstract methods Doinbackground (Params ... p) to implement tasks in this method, such as downloading or uploading on the Internet. Asynctask defines three generic types of params,progress and result.

1, Params start task execution of input parameters, such as HTTP request URL, upload file path, etc.;

2, the Progress background task execution percentage;

3, result background to perform the task of the final return results, such as String.

The execution of Asynctask is divided into four steps, similar to the Tasklistener defined earlier. Each step corresponds to a callback method, it should be noted that these methods should not be called by the application, developers need to do is to implement these methods. These methods are invoked automatically during the execution of a task.

1, OnPreExecute (), this method will be invoked by the UI thread before performing the actual background operation. You can do some preparation work in this method, such as displaying a progress bar on the interface.

2, Doinbackground (Params ...), will be executed immediately after the OnPreExecute method is executed, which runs in the background thread. This will be the main responsibility for performing the time-consuming background computing work. You can call the Publishprogress method to update the real-time task progress. This method is an abstract method that must be implemented by subclasses.

3, Onprogressupdate (Progress ...), after the Publishprogress method is invoked, UI thread will call this method to show the progress of the task in the interface, for example, through a progress bar.

4, OnPostExecute (result), after Doinbackground execution, the OnPostExecute method will be invoked by the UI thread, and the results of the background calculation will be passed to UI thread by this method.

The following two lines are used in the main process to begin the asynchronous task:

Mtask = new MyTask (); 

In the Doinbackground () function, params[0] and params[1] do not correspond to the first and second variables of execute ().

Private class MyTask extends Asynctask<string, Integer, string>{@Override protected void OnPostExecute (String result)   
    {///Final result display mtvprogress.settext (results); 
    @Override protected void OnPreExecute () {//preparatory work before the start Mtvprogress.settext ("Loading ..."); } @Override protected void Onprogressupdate (Integer ... values) {//Show progress mpgbar.setprogress (value 
      S[0]); 
    Mtvprogress.settext ("Loading ..." + values[0] + "%"); 
      @Override protected string Doinbackground (String ... params) {//here Params[0] and Params[1] is the two argument that execute passed in 
      String FilePath = params[0]; 
      String uploadurl = params[1]; 
      The following is the phone-side upload file code String end = "\ r \ n"; 
      String Twohyphens = "--"; 
      String boundary = "Hu Jintao"; 
        try {URL url = new URL (uploadurl); 
        HttpURLConnection httpurlconnection = (httpurlconnection) URL. OpenConnection (); HttpurlConnection.setdoinput (TRUE); 
        Httpurlconnection.setdooutput (TRUE); 
        Httpurlconnection.setusecaches (FALSE); 
        Httpurlconnection.setrequestmethod ("POST"); 
        Httpurlconnection.setconnecttimeout (6*1000); 
        Httpurlconnection.setrequestproperty ("Connection", "keep-alive"); 
        Httpurlconnection.setrequestproperty ("Charset", "UTF-8"); 
 
        Httpurlconnection.setrequestproperty ("Content-type", "multipart/form-data;boundary=" + boundary); 
        DataOutputStream dos = new DataOutputStream (httpurlconnection. Getoutputstream ()); 
        Dos.writebytes (twohyphens + boundary + end); Dos. Writebytes ("Content-disposition:form-data; Name=\ "File\"; 
        Filename=\ "" + filepath.substring (Filepath.lastindexof ("/") + 1) + "\" + end); 
 
        Dos.writebytes (end); 
        Gets the total size of the file FileInputStream fis = new FileInputStream (FilePath); Long total = Fis.availablE (); byte[] buffer = new byte[8192]; 
        8k int count = 0; 
        int length = 0; 
          while ((count = fis.read (buffer))!=-1) {dos.write (buffer, 0, count); 
          Gets the progress of the call publishprogress () length + = count; 
          Publishprogress ((int) ((Length/(float) total) * 100)); 
        Here is the test in order to demonstrate progress, hibernate 500 milliseconds, normal should remove Thread.Sleep (500); 
        } fis.close (); 
        Dos.writebytes (end); 
        Dos.writebytes (twohyphens + boundary + twohyphens + end); 
 
        Dos.flush (); 
        InputStream is = Httpurlconnection.getinputstream (); 
        InputStreamReader ISR = new InputStreamReader (IS, "utf-8"); 
        BufferedReader br = new BufferedReader (ISR); 
        @SuppressWarnings ("unused") String result = Br.readline (); 
        Dos.close (); 
        Is.close (); 
    Return "upload success"; 
      }catch (Exception e) {e.printstacktrace (); 
    Return "Upload failed"; 
 }   
  }

The interface can be as long as a progress bar ProgressBar and a textview for display.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.