Android simple music playing example

Service translated into Chinese is a service. Students familiar with Windows system must be very familiar with it. The service function in Android is similar to that in windows, that is, an invisible process is executed in the background. The service in Android is different from activity. It can't interact with users and start itself. It runs in the background. If we exit the application, the service process doesn't end, it still runs in the background. For example, we open a music player to listen to music and want to do other things while listening to music, such as chatting Q on the Internet Or browse the news on the Internet. In this case, we need to use the service service. Let's illustrate the service life cycle and service usage with a simple example of a music player. The following is the program structure diagram of the music player demo:

Android service life cycle:

The service life cycle in Android is not very complex, but inherits the three methods oncreate(), onstart(), ondestory(). When we start the service for the first time, we call oncreate() -- > onstart() methods. When we stop the service, we call ondestory() method. If the service has been started, the second time you start the same service, you just call the OnStart () method. Use of Android service: 1. Referring to the above program structure diagram, we can create an Android program, create an activity in the SRC directory, and a service class inherited from the service class; At the same time, create a raw folder under the res directory of the resource folder to store audio files. For example, put the music.mp3 music file in this directory. The main interface of the program is as follows:

2. The source code of the main.xml file in the layout Directory:

3. Musicservice.java source code in SRC Directory:

4. Musicserviceactivity source code in SRC Directory:

5. Finally, don't forget to add the registration of the service in the androidmanifest. XML configuration file. That is, add < service Android: name = ". Musicservice" / > in the application node to register. 6. Let's take a look at the service life cycle displayed in the log. E after the program runs

7. Let's check the music playback service just started in the Android terminal device to see if the service of the program is still running after we exit the program? Follow the steps below: menu -- > settings -- > applications -- > running services. You can see which services are running in the pop-up running services.

In this way, we can see that after we exit the program, because the service is still running in the background, our music can continue to play. In this way, we can enjoy music, chat QQ, or browse the news and so on.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>