Background music Add

Source: Internet
Author: User

Start a service to play music in the background, bind the service to the activity so that their life cycle is the same, and the music will stop after the activity is launched.
Here's a simple example:
1, Musicserver.java class, content for
Import Android.app.Service;
Import android.content.Intent;
Import Android.media.MediaPlayer;
Import Android.os.IBinder;

public class Musicserver extends Service {
Private MediaPlayer MediaPlayer;
@Override
Public IBinder Onbind (Intent Intent) {
TODO auto-generated Method Stub
return null;
}
@Override
public void OnStart (Intent intent,int startid) {
Super.onstart (Intent, Startid);
if (mediaplayer==null) {
MediaPlayer = Mediaplayer.create (this, R.raw.yuanyiwei);
Mediaplayer.setlooping (TRUE);
Mediaplayer.start ();
}
}
@Override
public void OnDestroy () {
TODO auto-generated Method Stub
Super.ondestroy ();
Mediaplayer.stop ();
}
} 

3. Place the song in the Raw folder under the name Yuanyiwei  
4. Add code   in activity;
Private Intent serviceintent = new Intent ("Com.angel.Android.MUSIC");  
OnCreate method Add StartService (serviceintent);  

5. Exit the page to add  
//Prevent music from stopping after exiting the issue Span class= "Apple-converted-space" > 
protected void OnDestroy () {//TODO auto-generated method Stub 
Super.ondestroy ();  
StopService (serviceintent); System.exit (0); }

Add background music

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.