Android file upload example with progress bar (using asynctask asynchronous task)
In the recent project, we need to do a function of uploading files with a progress bar. After learning asynctask, it is more convenient to use. Just implement several methods. In addition, we have made a very simple demo. I hope it can be helpful to you. Just set the file path and server IP in the program.
Screenshot of demo running:
Asynctask is an abstract class. Its subclasses must implement the abstract method doinbackground (params... P), which implements the execution of tasks, such as online download or upload. Asynctask defines three generic types params, progress and result.
1. Params input parameters for starting task execution, such as URL of HTTP request, path of uploaded file, etc;
2. Progress percentage of background tasks executed;
3. Result the final returned result of the background execution task, 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. What developers need to do is to implement these methods. These methods are called automatically during the execution of the task.
1. Onpreexecute(), which will be called by UI thread before performing the actual background operation. You can do some preparatory 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. It will be mainly responsible for the time-consuming background computing. You can call the publishprogress method to update the real-time task progress. This method is an abstract method, and subclasses must implement it.
3. Onprogressupdate (Progress...), after the publishprogress method is called, the UI thread will call this method to display the progress of the task on the interface, for example, through a progress bar.
4. Onpostexecute (result). After doinbackground execution is completed, onpostexecute method will be called by UI thread, and the background calculation results will be passed to UI thread through this method
The main process starts the asynchronous task with the following two lines:
In the doinbackground() function, params [0] and params [1] respectively correspond to the first and second variables of execute().
In the interface, you only need a progress bar and a textview for display.
The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.