Run Interface
Project directory
Playmusicactivity. Java
Package gogler. myandroid;
Import Android. App. activity;
Import Android. content. intent;
Import Android. OS. Bundle;
Import Android. View. view;
Import Android. View. View. onclicklistener;
Import Android. widget. Button;
Public class playmusicactivity extends activity {
/** Called when the activity is first created .*/
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
// Obtain the button object from the main. xml Layout
Button button_start = (button) findviewbyid (R. Id. playbt );
Button button_stop = (button) findviewbyid (R. Id. stopbt );
// Set button listening
Button_start.setonclicklistener (start );
Button_stop.setonclicklistener (STOP );
}
// Start button
Private onclicklistener start = new onclicklistener ()
{
Public void onclick (view V)
{
// Enable service
Startservice (new intent ("android. Intent. Action. Music "));
}
};
// Stop button
Private onclicklistener stop = new onclicklistener ()
{
Public void onclick (view V)
{
// Stop the service
Stopservice (new intent ("android. Intent. Action. Music "));
}
};
}
Musicplayerservice. Java
Package gogler. myandroid;
Import Android. App. Service;
Import Android. content. intent;
Import Android. Media. mediaplayer;
Import Android. OS. ibinder;
Public class musicplayerservice extends Service {
Private mediaplayer player;
@ Override
Public ibinder onbind (intent ){
// Todo auto-generated method stub
Return NULL;
}
@ Override
Public void ondestroy (){
// Todo auto-generated method stub
Super. ondestroy ();
// 3. Stop music
Player. Stop ();
}
@ Override
Public void onstart (intent, int startid ){
// Todo auto-generated method stub
Super. onstart (intent, startid );
// 1. Load music
// 2. Play Music
Player = mediaplayer. Create (this, R. Raw. tommaimairubsaktee );
Player. Start ();
}
}
Androidmanifest. xml
<? XML version = "1.0" encoding = "UTF-8"?>
<Manifest xmlns: Android = "http://schemas.android.com/apk/res/android"
Package = "gogler. myandroid"
Android: versioncode = "1"
Android: versionname = "1.0" type = "codeph" text = "/codeph">
<Uses-SDK Android: minsdkversion = "1"/>
<Application
Android: icon = "@ drawable/Russia"
Android: Label = "@ string/app_name">
<Activity
Android: icon = "@ drawable/Russia"
Android: Label = "@ string/app_name"
Android: Name = ". playmusicactivity">
<Intent-filter>
<Action Android: Name = "android. Intent. Action. Main"/>
<Category Android: Name = "android. Intent. Category. launcher"/>
</Intent-filter>
</Activity>
<Service
Android: Name = ". musicplayerservice">
<Intent-filter>
<Action Android: Name = "android. Intent. Action. Music"/>
</Intent-filter>
</Service>
</Application>
</Manifest>
Package and download code
Http://download.csdn.net/download/gogler/3727632