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

问题描述:

我正在使用以下代码获取存储在SD卡中的所有歌曲。这段代码为什么需要很长时间?

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

那么为什么会出现这种代码需要很长时间恢复的歌曲列表中。 我已将这段代码包含在一个函数中,该函数从播放器播放列表中的oncreate方法中调用。
这是发生了什么事。
1:当我的android ph第一次执行应用程序运行时,播放列表没有任何显示,因此被看作是空的。
2:好了之后 - > 30秒,当我再次呼叫播放列表时,它立即返回所有歌曲。

因此,给人的感觉好像这件事需要时间来执行?
这是为什么发生?

+0

在背景上运行它,然后加载可能有太多 – Trikaldarshi

+0

@Photon我也尝试使用相同的线程,但相反,造成不必要的复杂性,没有结果 – user2714061

如何使用异步任务,读取文件或下载的东西,需要需要用户等待的时间,你必须考虑使用异步任务用于此目的,

1:从开发人员参考我们有: AsyncTask使适当和简单的使用UI线程。该类允许执行后台操作并在UI线程上发布结果,而无需操纵线程和/或处理程序。 http://developer.android.com/reference/android/os/AsyncTask.html

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

2:所以,你可能包括一个异步任务类为:

new DoBackgroundTask().execute(URL); 

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. 

这的AsyncTask可以从你onCreate方法通过调用其执行方法并传递参数给它叫

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

+0

Thankyou @twntee我肯定会包括这个! – user2714061