First, Musicactivity.java
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_musicservice);
Button start= (button) Findviewbyid (R.id.button_start);
Button stop= (button) Findviewbyid (r.id.button_stop);
Start.setonclicklistener (New Button.onclicklistener () {
public void OnClick (View arg0) {
StartService (New Intent ("Com.yarin.Android.MUSIC"));
}
});
Stop.setonclicklistener (New Button.onclicklistener () {
public void OnClick (View arg0) {
StopService (New Intent ("Com.yarin.Android.MUSIC"));
}
});
}
Second, Musicservice.java
private static final String tag= "Musicservice";
Create a MediaPlayer Object
Private MediaPlayer player;
@Override
Public IBinder Onbind (Intent arg0) {
return null;
}
@Override
public void OnCreate () {
Super.oncreate ();
try {
Loading music files
Player = Mediaplayer.create (this, r.raw.speedwagon);//raw Directory has Speedwagon.mp3 file
Start playback
Player.start ();
} catch (Exception e) {
LOG.I (TAG, e.tostring ());
}
}
@Override
public void OnDestroy () {
Super.ondestroy ();
try {
Player.stop ();
} catch (Exception e) {
LOG.I (TAG, e.tostring ());
}
}
Third, Androidmanifest.xml
<!--music playback Control--
<service android:name= ". Musicservice ">
<intent-filter>
<action android:name= "Com.yarin.Android.MUSIC" >
</action>
<category android:name= "Android.intent.category.default" >
</category>
</intent-filter>
</service>
<activity
Android:name= ". Musicactivity "
Android:label= "examples_0303" >
<intent-filter>
<action android:name= "Android.intent.action.MAIN"/>
<category android:name= "Android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
Music playback controls