为什么这段代码需要很长时间?

时间:2013-09-01 09:08:29

标签: android performance android-mediaplayer

我使用以下代码获取存储在SD卡中的所有歌曲。

https://stackoverflow.com/a/12227047/2714061

为什么这段代码需要很长时间才能返回此歌曲列表。 我已将此代码包含在一个函数中,该函数是从播放器播放列表中的oncreate方法调用的 这就是发生的事 1:当我的android ph上第一次执行应用程序运行时,播放列表没有显示任何内容,因此看起来是空的。
2:以后 - 例如 - > 30秒,当我再次呼叫播放列表时,它立即返回所有歌曲。

因此,感觉好像这件事需要时间来执行? 为什么会这样?

1 个答案:

答案 0 :(得分:2)

如何使用异步任务,读取文件或下载某些内容,需要时间等待用户等待,您必须考虑为此目的使用异步任务,

1:从开发人员参考资料中我们有: AsyncTask可以正确,方便地使用UI线程。此类允许执行后台操作并在UI线程上发布结果,而无需操作线程和/或处理程序。 http://developer.android.com/reference/android/os/AsyncTask.html

异步任务由3种泛型类型定义,称为Params,Progress和Result,以及4个步骤,分别称为onPreExecute,doInBackground,onProgressUpdate和onPostExecute。

2:因此,您可以将Async任务类包含为:

 class DoBackgroundTask extends AsyncTask<URL, Void, ArrayList> {
           /*
             URL is the file directory or URL to be fetched, remember we can pass an array of URLs, 
            Void is simple void for the progress parameter, you may change it to Integer or Double if you also want to do something on progress,
            Arraylist is the type of object returned by doInBackground() method.

           */
    @Override
    protected ArrayList doInBackground(URL... url) {
     //Do your background work here
     //i.e. fetch your file list here

              return fileList; // return your fileList as an ArrayList

    }

    protected void onPostExecute(ArrayList result) {

    //Do updates on GUI here
     //i.e. fetch your file list from result and show on GUI

    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        // Do something on progress update
    }

}
//Meanwhile, you may show a progressbar while the files load, or are fetched.

可以通过调用其execute方法并将参数传递给它来从您的onCreate方法调用此AsyncTask:

 new DoBackgroundTask().execute(URL);

3:最后,还有一个关于AsyncTasks的非常好的教程,http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html