Let's talk about the good programming habits and use ListView and AsyncTask to download songs asynchronously.

Source: Internet
Author: User

In the previous blog, I introduced how to use AsyncTask to Implement Asynchronous processing of time-consuming operations. This time I will introduce a small project (Small Module) for downloading songs based on all the content mentioned above ). Before introducing it, I would like to share some good programming habits with you so that our programmers can become more readable and easy to modify members.

1: The class name must start with an uppercase letter and the method name must start with a lowercase letter. It is best to express the meaning of this class or method in English. Presumably this is the most basic requirement.

2: If you need to implement interfaces or inherit a few simple class codes, we recommend that you use anonymous classes to write them, such as button Listening Classes.

3: If the implementation interface or inherited class code is complex, we recommend that you re-write a class to inherit or implement the interface, such as a thread, the advantage is that you can use the constructor to input parameters to the class if you need to input parameters externally.

4: If a class needs to use other class variables (for example, listening by pressing a key to change the text ). At this time, you can write an internal class or an anonymous internal class, so that you can directly use the required class variables.

5: During programming, if a number or string appears in several places at the same time and the value remains unchanged, such as the URL or screen size ), in this case, we can define this variable as a static constant (it is best to name the constant in uppercase). When we need the value of this constant, we only need to change the constant value, no need to find all the places to modify

6: if there are more classes, it is best to start to use the package classification, for example, Android Activity Package dedicated Activity, util package dedicated tool class, app package dedicated application class, etc.

7: The member variable is preceded by a letter m.

The above is my summary. I hope to help you. Next I will start to download the song Project (this project requires a computer to connect to the network)

1: Write the row layout, get the listView object, and set the adapter Class Optimization and Data encapsulation (the usage of listView is described in the previous blog, so I will not talk about it here ), line Layout pictures are used to hold the artist's photos. The title displays the song name, the sub-title displays the singer name, the progress bar shows the download progress, and the button enables the download function. The row layout is as follows:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/0629246193-0.jpg "title =" EF} P51NGRFZ4M77A @~ 0 ~ 9%Y.jpg "/>

2: encapsulate the required data into an object and store these objects in a container


// Private ArrayList <Itemdata> mData = new ArrayList <Itemdata> (); // singer name array private String [] name = new String [] {"Hu Xia", "Jay Chou", "Wang Lihong "}; // object song name private String [] music = new String [] {"those years", "Longmen Inn", "Still love you "}; // corresponding singer name value (because sdcard can only export letters, you must use Pinyin to store the song name) private String [] music_value = new String [] {"naxienian", "longmenkezhan ", "yiranaini"}; // The private int [] picture = new int [] {R. drawable. huxia, R. drawable. zhouji Elun, R. drawable. wanglihong}; // corresponding private String [] address = new String [] {"http://zhangmenshiting.baidu.com/data2/music/46614034/138444821376874061128.mp3? Xcode = 0b7508b24c5c9539814d252fc8260c557a48f91107b5ffaf "," http://zhangmenshiting.baidu.com/data2/music/35479592/314965631376820061128.mp3? Xcode = 29b8efeab72ee1f188009d4d5095c7d468b2ac04a0a9b4cc "," http://zhangmenshiting.baidu.com/data2/music/10512583/105098561376809261128.mp3? Xcode = 67f6c2ca000000003a5741df3072eabfcba9740086dc7de35a "};


for (int i = 0; i < 3; i++) {  Itemdata itemdata = new Itemdata(music[i], name[i], picture[i]);  mData.add(itemdata);}


4: Get all the control objects in the row layout, set listening events in the button, start the asynchronous task when the button is pressed, and set the progressBar object and button Object of the corresponding row layout, the title object is passed into the asynchronous class (the bar object is used to change the progress bar based on the number of downloads during download, and the button is used to restore the clickable status after the download is complete, the title object indicates which song to be downloaded after the download is complete. The Code is as follows (the holder object mentioned in listView optimization here ).


Layout = getLayoutInflater (). inflate (R. layout. list, null); holder = new ViewHolder (); holder. mImage = (ImageView) layout. findViewById (R. id. imageView1); holder. mTitle = (TextView) layout. findViewById (R. id. textView1); holder. mSubtitle = (TextView) layout. findViewById (R. id. textView2); holder. bar = (ProgressBar) layout. findViewById (R. id. progressBar1); holder. btn = (Button) layout. findViewById (R. id. button1); final Button btn = (Button) layout. findViewById (R. id. button1); final ProgressBar bar = (ProgressBar) layout. findViewById (R. id. progressBar1); final TextView title = (TextView) layout. findViewById (R. id. textView1); holder. btn. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// set the button to not clickbtn. setEnabled (false); // start the task and pass the required parameters to new MyTask (bar, title, btn, name_value [position]). execute (address [position]) ;}}); 3: One-Step task

5. Add the corresponding values to the object control.

Itemdata itemdata = mData.get(position);holder.mImage.setImageResource(itemdata.image);holder.mTitle.setText(itemdata.title);              holder.mSubtitle.setText(itemdata.subtitle);

6: The doInBackgroud method in the asynchronous class that inherits asyncTask is used to download songs. The Code is as follows:

FileOutputStream fos = null; InputStream is = null; try {// obtain url object URL = new url (params [0]); // obtain URLconne object URLConnection openConnection = URL. openConnection (); // get the file size in bytes) int length = openConnection. getContentLength (); // set the maximum value of the progress bar to the file size bar. setMax (length); // The obtained input stream is = openConnection. getInputStream (); // obtain the absolute path of the sdCard File SDCardPath = Environment. getExternalStorageDirectory (). getAbsoluteFil E (); // create an output stream object and download the object to the sdCard directory. fos = new FileOutputStream (SDCardPath + "/" + music_value + ". mp3 "); byte [] buffer = new byte [1024]; // obtain the length of the specific bytes for each download. int len = is. read (buffer); while (len! =-1) {// call this method to enter the ononProgressUpdate () method and set the progress bar publishProgress (len); fos. write (buffer); len = is. read (buffer);} fos. flush ();} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} finally {if (fos! = Null) {try {fos. close ();} catch (IOException e) {e. printStackTrace ();} if (is! = Null) {try {is. close ();} catch (IOException e) {e. printStackTrace () ;}}// after the download is complete, the song name of the corresponding song is returned, and the onPostExecute method is used to process the return title. getText (). toString () + "download completed ";

7: Modify the progress bar in the onProgressUpdate (Integer... values) Method

@Overrideprotected void onProgressUpdate(Integer... values) {    super.onProgressUpdate(values);    bar.setProgress(bar.getProgress()+values[0]);}

8: After the download is complete, use the Toast method in the onPostExecute (String result) method to notify the user that the download is complete and set the button to available.

@ Overrideprotected void onPostExecute (String result) {super. onPostExecute (result); // The interface prompts you to download Toast. makeText (MainActivity. this, result, Toast. LENGTH_LONG ). show (); // The button is set to available btn. setEnabled (true );}

9: Set permissions (here we need to download and write the two permissions for sdCard from the Network), and configure AndroidManifest. xml in the configuration file)

<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

10: All done. (In the download process, when you click to download the three songs, we find that only the progress bar of the first song is going because of Android 4.2, in fact, the asynchronous task has already started. When the first song is downloaded, it will automatically continue to the second song.

650) this. width = 650; "src =" http://img1.51cto.com/attachment/201308/204112324.jpg "title =" 8 (YRL '6] MA5F ~ _Eqri4l1__x.jpg "/>

Prompt when download is complete

650) this. width = 650; "src =" http://img1.51cto.com/attachment/201308/204206289.jpg "title =" _1__o@03uz(6rn_1_edt6o1_1_1.jpg "/>

All downloaded files are in the SDCard directory.

650) this. width = 650; "src =" http://img1.51cto.com/attachment/201308/204355854.jpg "title =" 3BB26647-0F37-42E2-90C5-8CF776382263.jpg "/>

Only three songs can be created for time. Here, I will introduce you to the basic usage of the android thread. I will upload the complete code to my download. If you need it, you can download it with the name DownLoadMusic. Next time, I will introduce the creation and lifecycle of Activity, one of the four main components.

This article from the "android technology" blog, please be sure to keep this source http://7735447.blog.51cto.com/7725447/1279226

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.