Why does this code take a long time?

懵懂的女人 提交于 2019-12-12 05:13:49

问题


I am using this following code for getting all songs stored in the sdcard.

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

Well why does this code take so long to return this list of songs. I have included this code in a function which is called from the oncreate method in my player's playlist.
This is what happens.
1: When the application runs is executed for the first time on my android ph, the playlist has nothing to show, and hence is seen empty.
2: Well after for instance-> 30sec when I again call for the playlist it returns instantly all the songs.

Hence, giving the feel as though this thing takes time to execute?
Why does this happen?


回答1:


How about using an asynchronous task, reading a file or downloading something, takes time that requires the user to wait, you must think of using an Asynchronous task for this purpose,

1: From the developer reference we have : AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. http://developer.android.com/reference/android/os/AsyncTask.html

An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

2: So you may include an Async task class as:

 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.

This AsyncTask can be called from you onCreate method by calling its execute method and passing the arguments to it:

 new DoBackgroundTask().execute(URL);

3: And at last, there is also a very nice tutorial about AsyncTasks here, http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html



来源:https://stackoverflow.com/questions/18556912/why-does-this-code-take-a-long-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!