Andriod Small Item--online music player

Source: Internet
Author: User
Tags call back

Andriod Small Item--online music player


Android online music player

Since freshman year has started to self-study Java and Android , it has been almost one years.

Finally to begin to do the project in the stage of actual combat. First DIY online music player.


The following features are implemented:

This player can asynchronously read and parse JSON data from a simple server built on a native computer , play Music , switch music , display time , and Shows the playback progress .


The program has three interfaces, splash screen, music list, player page, and can be clicked into the play screen via the music list.


This article only presumably wrote about the idea of implementation, describing some key areas.

The source code is also provided at the end of the article and can be Download .




This is the playback interface :






The specific idea is as follows: Total 6 steps


1. build simple server and interface design

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

Here we choose the XAMPP Kit, we use the Apache server.

Of course, you can choose the computer with the IIS is also possible, you can open it in the Control Panel. There's no more talking here.

If you're using XAMPP like me , open X:\xampp\htdocs .

Here is the root directory of the Apache server.

We will be able to access it here by entering localhost in the browser , or the computer IP under the LAN .

We created a new folder in htdocs and then copied 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": "Against the Grain", "Singer": "Akon", "MP3": "Music/101.mp3"},

{"Name": "Entre Toi Et Moi", "Singer": "Mathieu Edward", "MP3": "Music/102.mp3"}]

Well, our simple server is done.

Our interface is:

Http://localhost/music/music.json

The directory is as follows:



2. New Project and file

With the Times, we use Android Studio 2.0 , which was released shortly before Google, as a development environment.

Open it New project , take a name.

Then we create the directory:

Activity--- is our event class, and all of our activities are established here

Adapter-- adapter, save Some like a ListView Adapter etc.

Model- entity class for storing Music entities.

Server-- service, we will set up the background service code here

util-- tools, we will design some of the functions used to play the concert, and then encapsulate it into classes, easy to use


After the completion of the establishment should:


3. Design the start-up interface,

The splash screen is similar to the one on the moon when it is opened. Create a new splashactivity

We need to get the splash screen to show about two seconds, then end this 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 the anonymous interface and start another activity in the Run method, which we one go.

public class Splashactivity extends Appcompatactivity {    @Override    protected void onCreate (@Nullable Bundle Savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.logo_show_layout);//Start Screen code:        new Handler (). postdelayed (New Runnable () {            @Override Public            void Run () {              startactivity (new Intent (Splashactivity.this,musiclistmainactivity.class));                SplashActivity.this.finish ();            }        },1500);}    }


4. Write a list activity that displays music information.

New Musiclistmainactivity
This activity is the class that starts after the end of the start interface. This class will connect to the server, get and parse the JSON data. Obviously this requires a thread to be processed asynchronously, otherwise the network is connected or blocked to the main thread, causing the ANR to occur.
Here we use Asynctask,asynctask have a lot of shortcomings you should know, if you can still use Java callback to combine with the thread. or any other way
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);}

Write 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) {Conne Ction.disconnect ();}}}). Start ();}



Then we can call it where we need it, pass in the corresponding parameter, and 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 is still not updatable because it is still part of the child thread. Also need Handler or runonuithread (.. ) To implement the update UI


Well, let's take a look at how Asynctask can achieve this:
First create a new Httpresponsehandle class, put it in the Util folder, inherit from Asynctask<string, Void, string>

Asynctask This class uses Java generics, the first parameter is the arguments passed in at execution time, the second is the parameters of the progress display, and if you need to show progress such as 41%, this cannot be empty. The third parameter is the return type after the asynchronous execution completes.

Protected string Doinbackground (String ... params) @Overrideprotected void OnPostExecute (string result) {    OnComplete (result);}

After we have inherited these two functions, the first function can be time-consuming, because Android implements the asynchronous thread at the bottom, the second function will call back after the completion of Doinbackground, and pass in the Doinbackground return value. This intermediate operation is done automatically. At this time our background operation has been completed. We built an abstract function, public abstract void OnComplete (String result) in Httpresponsehandle, to implement an effect similar to that of a just-used interface callback.
This abstract function will receive the parsed data and we will call it later in Musiclistmainactivity.
In the implementation of Musiclistmainactivity:

Httpresponsehandle httpresponsehandle = new Httpresponsehandle () {  //executed to OnComplete instructions we have written the asynchronous processing has successfully read the data,// Because it is JSON-formatted data, we can start parsing it in OnComplete  @Override public    void OnComplete (String result) {           //Receive data here, Start parsing JSON data        }};

The asynchronous processing we wrote is not automatically started, we need to call the Execute () function:

After the call executes Doinbackground (), and execute passes the arguments to it doinbackgroundhttpresponsehandle.execute ("Http://192.168.41.3/music/music.json");


5. Design ideas of service class
The service class performs different operations by receiving the judging parameters.
It is important to note that Android services do not directly perform time-consuming operations, or need to open their own multi-threaded. Calling Mediaplay.prepare () is a time-consuming operation that causes the main thread to block.
It's good to use Prepareasync () here, or else you'll have to make a thread or other way to handle the blockage.


6.MusicUtil Tool Class
The implementation of the initial music, music playback, pause, but also to achieve real-time update music progress.
The progress of music is realized in this way:

Set yourself to perform a handler of 500 milliseconds per second by sending a broadcast that notifies Musicplayer to make UI updates.
There is also a musicmediautil class that may not be available, and this class can return the MediaPlayer object, just like the new MediaPlayer () effect. This class is designed because some errors are reported when Setdatasource switch songs. I refer to a lot of information and say it is a trivial error (E/mediaplayer:should has subtitle controller already set), which is handled according to the method provided by StackOverflow. -This kind of direct use of Java reflection, the original code slightly modified, so that there will be no e/mediaplayer:should ... 's mistake.



All right, finally, how does the project work?


Turn on the server, first of all, make sure that the computer and your phone in the same LAN, the simplest way is that they connect to a Wi-Fi,

Then the computer presses the Windows key +r input cmd opens the command line, enters Ipconfig IPv4 is your computer's IP, the IP it fills in musiclistmainactivity inside root= "" inside. This way the phone can connect to the computer's server properly.


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


Ps.

Beginner's article, Big god please tap!!

The first time to write about the Android blog, we have to encourage me ha ~.



http://download.csdn.net/detail/sunkes/9495726









Andriod Small Item--online music player

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.