Sometimes, we need to traverse all the files in the system. Usually the number of files in a mobile product is very large, we need to open an asynchronous task for this matter, otherwise it will cause the ANR to crash the application.
About Asynctask
asynctask<params,progress,result> This class is very handy for lightweight asynchronous task classes. It provides tasks, tasks, post-task methods, and so on, which can be very simple to complete the creation of asynchronous tasks.
Params: Type of input parameter that initiates a task execution
Progress: The type of progress value that the background task completed
Result: The type of the result returned after the background execution task finishes
Therefore, the establishment of asynctask can be divided into two steps.
First, rewrite the Asynctask task before completion, complete the method after completion.
classScansdmusicextendsAsynctask<string, Integer, integer>{ProgressDialog dialog2; Context Mycontext; PublicScansdmusic (Context context) {Mycontext=context; } @OverrideprotectedInteger doinbackground (String ... params) {getallfiles (path); for(inti = 0; I < musicinfos.size (); i++) {Music_list.additem (Musicinfos.get (i). GetTitle (), Musicinfos.get (i). Getauthor ()); //put music information in a list } return NULL; } @Overrideprotected voidOnPreExecute () {Super. OnPreExecute (); DIALOG2= Progressdialog.show (mycontext, "hint", "struggling to find in ..."); Dialog2.show (); Music_list=Newmusic_list (mycontext); Simpleadapter=music_list.showlist (mycontext); Musicinfos=NewArraylist<music_info>(); } @Overrideprotected voidonpostexecute (Integer integer) {Super. OnPostExecute (integer); Dialog2.cancel (); Listview.setadapter (Simpleadapter); } }
As shown above
OnPreExecute is before the task starts, I show the dialog box being loaded and create the objects that are needed to perform the task.
OnPostExecute is the end of the task, in the method I closed the display of the Load dialog box and updated the display list.
Doinbackground is a task that needs to be performed in the background, by recursively traversing all the files in the SD card and listing the required information in the ListView list.
II. Create and open an asynchronous task
Scansdmusic scansdmusic=New scansdmusic (this); Scansdmusic.execute ("0");
About Traversal
Iterate through the root directory recursively, and enter its subdirectories if the target is not a file.
//traverse the file path and all its sub-paths, and extract the information Private voidgetallfiles (file root) {file files[]=Root.listfiles (); if(Files! =NULL){ for(File f:files) {if(F.isdirectory ()) {getallfiles (f); }Else{ Try { if(F.getcanonicalpath (). Contains (". mp3") ) {String name=music_info.getsdmusictitle (f);//Intercept and set its file nameMusic_info Music_info =Newmusic_info (name); Music_info.setindex (f); Musicinfos.add (Music_info); } } Catch(IOException e) {e.printstacktrace (); } } } } }
Above.
Simple file traversal using Asynctask