使用AsyncTask简单的文件遍历

  有时候,我们需要遍历系统中的所有文件。通常一个移动产品内的文件数量是非常巨大的,我们需要为这件事开启一个异步任务,否则将引起ANR,使应用崩溃。

  关于AsyncTask

  AsyncTask<Params,Progress,Result>这个类是非常方便的轻量级异步任务类。它提供了任务前,任务,任务后等方法,可以非常简单地完成异步任务的建立。

  Params:启动任务执行的输入参数的类型

  Progress:后台任务完成的进度值的类型

  Result:后台执行任务完成后返回结果的类型

  因此,关于AsyncTask的建立可分为两步。

  一、重写AsyncTask的任务完成前,完成中,完成后的方法。

    class ScanSDMusic extends AsyncTask<String , Integer , Integer>{
        ProgressDialog dialog2 ;
        Context myContext;
        public ScanSDMusic(Context context){
            myContext=context;
        }
        @Override
        protected Integer doInBackground(String... params) {
            getAllFiles(path);

            for(int i = 0 ; i < musicInfos.size() ; i++) {
                music_list.addItem(musicInfos.get(i).getTitle(), musicInfos.get(i).getAuthor());   //将音乐信息逐一放入列表中
            }

            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog2 = ProgressDialog.show(myContext , "提示", "奋力寻找中……");
            dialog2.show();
            music_list=new Music_List(myContext);

            simpleAdapter=music_list.showList(myContext);
            musicInfos = new ArrayList<Music_Info>();
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            dialog2.cancel();
            listView.setAdapter(simpleAdapter);

        }
    }

  如上所示

  onPreExecute是任务开始前,方法中我显示了正在加载的对话框,并创建了执行任务时所需要的对象。

  onPostExecute是任务结束后,方法中我关闭了加载对话框的显示,并更新的显示列表。

  doInBackground是后台需要执行的任务,方法中,我通过递归遍历SD卡所有文件,并将需要的信息列入ListView列表中。

  二、创建并开启异步任务

        ScanSDMusic scanSDMusic=new ScanSDMusic(this);
        scanSDMusic.execute("0");

  

  值得注意的是,上面的写法是很危险的!

  因为我们在调用异步任务的方法时会打开一个新线程,但是,我们却没有考虑关闭它。于是,我们可以在onStop()的方法中,加入scanSDMusic.cancel(true);这样的方法,当Activity停止时,线程一起关闭。

  但是光这样做是不会有作用的,因为scanSDMusic.cancel(true);这个方法,其实它什么都不会做。对!它什么都不会做。那么,他的作用是什么呢?

  它仅仅是将AsyncTask对象中的线程状态,标记为cancel状态。标记为cancel状态有啥用?什么用都没有。不过你可以在子线程(doInBackground

)中来检查它的状态,用isCancelled()方法取出线程的状态,判断它,如果它是cancel状态,我们就return手动结束这个线程。

  关于遍历

  通过递归的方式,从根目录开始遍历,如果目标不是文件,则进入其子目录。

    // 遍历文件路径及其所有子路径,并提取信息
    private void getAllFiles(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);      //截取并设置其文件名
                            Music_Info music_info = new Music_Info(name);
                            music_info.setIndex(f);
                            musicInfos.add(music_info);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
原文地址:https://www.cnblogs.com/fishbone-lsy/p/4246847.html