Andriod small project-online music player

Source: Internet
Author: User

Andriod small project-online music player

Andriod small project-online music player

Android online music player

Java and Android have been self-taught since the freshman year, and it has been almost a year since now.

Finally, it's time to start the project practice. DIY online music player first.

The following functions are implemented:

This player can be used to build a simple server on a local computer.Asynchronously read and parse jsonData, playing music, ImplementationMusic Switching,Time Display, AndDisplay playback progress.

The program has three interfaces: startup screen, music list, and player page. You can click the music list to enter the playing interface.

This article only outlines implementation ideas and describes some key points.

The source code is provided at the end of the article.Download.

This is the playback interface:

The specific ideas are as follows: 6 steps in total

1. Simple Server and interface design

We need to build a simple server so that we can access the music files in our computer directory on the mobile client.

Here we chose the XAMPP suite. We use the Apache server.

Of course, you can also choose the built-in IIS on your computer. You can enable it in the control panel. I will not talk more here.

If you use XAMPP like me, open X: \ xampp \ htdocs

Here is the root directory of the Apache server.

You can enter localhost in your browser to access the site, or enter the IP address of your computer on the LAN.

Create a folder music in htdocs, and then copy some music to the folder we just created. Then create a new music. json file and put it together with our songs.

We can start editing json and open the Music. json we just created:

[{"Name": "AgainstTheGrain", "singer": "Akon", "mp3": "music/101.mp3 "},

{"Name": "EntreToiEtMoi", "singer": "MathieuEdward", "mp3": "music/102.mp3"}]

Now, our simple server is complete.

Our interface is:

Http: // localhost/music. json

The directory is as follows:

2. Create a project and a file

Keeping pace with the times, we use AndroidStudio2.0, which was recently released by Google, as the development environment.

Open it to create a project and get a name.

Then, create the directory:

Activity--- It is our activity class. All our activities are created here

Adapter-- Adapter, save some files such as ListView Adapter

Model-- Entity class, used to store Music objects.

Server-- Service, we will establish the background service code here

Util-- Tool. We will design some functions used for playing concerts and encapsulate them into classes for ease of use.

After the establishment, you should:

3. Design the startup interface,

The startup screen is similar to the page on the moon when it is opened. Create a SplashActivity

We need to display the startup screen for about two seconds, then end the activity and jump to the main program. The Code is as follows:

We use the postDelayed method in the Handler class. The first parameter is a Runnable interface,

We directly pass in and implement anonymous interfaces and start another activity in the run method. This step is done in one go.

Public class SplashActivity extends AppCompatActivity {@ Override protected void onCreate (@ Nullable Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. logo_show_layout); // code of the startup screen: new Handler (). postDelayed (new Runnable () {@ Override public void run () {startActivity (new Intent (SplashActivity. this, MusicListMainActivity. class); SplashActivity. this. finish () ;},1500 );}}


4. Compile a list of activities that display music information.

Create a MusicListMainActivity
This activity is the class started after the startup interface is complete. This class will connect to the server to obtain and parse json data. Obviously, this requires asynchronous processing of threads. Otherwise, the network connection or blocking to the main thread will lead to ANR.
Here we use AsyncTask. AsyncTask has many disadvantages. You should know that if you can still use java callback to combine with the thread. Or other methods
Although we use AsyncTask here, we still provide the java thread + Interface callback implementation method:

Interface Design:

public interface HttpCallbackListener {void onFinish(String response);void onError(Exception e);}

Compile related methods in the HttpUtil tool class:

Public static void sendHttpRequest (final String address, final HttpCallbackListener listener) {new Thread (new Runnable () {@ Overridepublic void run () {try {... while (line = reader. readLine ())! = Null) {response. append (line);} if (listener! = Null) {// callback onFinish () method listener. onFinish (response. toString () ;}} catch (Exception e) {if (listener! = Null) {// callback onError () method listener. onError (e) ;}} finally {if (connection! = Null) {connection. disconnect () ;}}}). start ();}



Then we can call it where we need it and pass in the corresponding parameters. The second parameter is the implementation of an anonymous interface.

HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {@Overridepublic void onFinish(final String response) {}@Overridepublic void onError(Exception e) {}})
Note that the UI cannot be updated in, because it still belongs to the Child thread. You also need Handler or runOnUiThread (...) to update the UI.

Okay. Let's take a look at how AsyncTask implements this function:
First, create the HttpResponseHandle class, put it in the Util folder, and inherit from AsyncTask

The AsyncTask class uses Java generics. The first parameter is the parameter passed in during execution, and the second parameter is the progress display. If you need to display the progress, for example, 41%, it cannot be blank here. The third parameter is the return type after the asynchronous execution is complete.

protected String doInBackground(String... params) @Overrideprotected void onPostExecute(String result) {    onComplete(result);}

After inheritance, we implement the above two functions. The first function can perform time-consuming operations. Because android implements asynchronous threads at the underlying layer, the second function will be called back after the completion of doInBackground, and input the doInBackground return value, which is automatically completed during the intermediate operation. The background operation is complete. In HttpResponseHandle, we create an abstract function public abstract void onComplete (String result) to implement the same effect as the callback method we just used.
This abstract function will receive parsed data and we will call it later in MusicListMainActivity.
Implementation of MusicListMainActivity:

 

HttpResponseHandle httpResponseHandle = new HttpResponseHandle () {// when onComplete is executed, it indicates that the asynchronous processing we have compiled has successfully read the data. // because the data is in JSON format, we can start parsing it in onComplete @ Override public void onComplete (String result) {// here accept data and start parsing json data }};

The asynchronous processing we write will not be automatically started. We need to call the execute () function:

 

// After the call, the system executes doinbackground((, and executetransmits the listener to doinbackgroundhttpresponsehandle.exe cute ("http: // 192.168.41.3/music. json ");


 

5. Service Design Ideas
The service class performs different operations by receiving and determining parameters.
It is worth noting that the android service does not directly perform time-consuming operations, but you still need to enable multithreading on your own. Calling MediaPlay. prepare () is a time-consuming operation, which will cause the main thread to block.
Use prepareAsync () here. Otherwise, you have to open the thread or use other methods to handle blocking.


6. MusicUtil tool class
It implements initialization of music, playing and pausing music, and updates the progress of music in real time.
The progress of music is achieved as follows:

Set the Handler to execute 500 ms per second to notify MusicPlayer to update the UI by sending a broadcast.
Another MusicMediaUtil class may not be used. This class can return MediaPlayer objects, which have the same effect as new MediaPlayer. This class is designed because some errors are reported when the setDataSource switches to a song. I have referenced a lot of materials, all of which are irrelevant errors (E/MediaPlayer: shocould have subtitle controller already set), which are handled according to the methods provided by StackOverFlow. -- This class directly uses JAVA reflection and slightly modifies the original code so that the error of E/MediaPlayer: shocould have... will not occur.

 


Now let's talk about how to run the project?

To enable the server, first make sure that the computer and your mobile phone are in the same LAN. The easiest way is to connect them to the same WiFi,

Press the Windows key + R and Enter cmd to open the command line. Enter ipconfig ipv4, which is the IP address of your computer. Enter the IP address in root = "" In MusicListMainActivity. In this way, the mobile phone can connect to the computer's server normally.

This is the end of the article. Thank you for your support.:)

 






Related Article

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.