This example describes the service usage of Android development. Share to everyone for your reference. The specific analysis is as follows:
Service is a long life cycle and no interface program.
The following is an example of playing mp3 to learn.
Watch Mainactivity.java first.
package com.example.servicetest;
Import android.app.Activity;
Import android.content.Intent;
Import Android.os.Bundle;
Import Android.view.Menu;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button; public class Mainactivity extends activity {@Override protected void onCreate (Bundle savedinstancestate) {sup
Er.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Button btnstart = (button) Findviewbyid (R.id.btnstart); Btnstart.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {Start
Service (New Intent ("Com.yarin.Android.MUSIC"));
}
});
Button Btnstop = (button) Findviewbyid (r.id.btnstop); Btnstop.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {Stopse
Rvice (New Intent ("Com.yarin.Android.MUSIC"));
}
}); }
}
Two buttons are defined on the interface.
And look at Musicservice.java.
Package com.example.servicetest;
Import Android.app.Service;
Import android.content.Intent;
Import Android.media.MediaPlayer;
Import Android.os.IBinder;
public class Musicservice extends Service {
private MediaPlayer player;
@Override public
IBinder onbind (Intent Intent) {
//TODO auto-generated method stub return
null;
} Public
void OnStart (Intent Intent, int startid) {
Super.onstart (Intent, startid);
Player = Mediaplayer.create (this, R.RAW.A);
Player.start ();
}
public void OnDestroy () {
Super.ondestroy ();
Player.stop ();
}
Defines what to do at start and destroy.
Create a new Raw folder under the Res directory and place the A.mp3 in the directory.
That way, when you click on the Start button, you can play the mp3 file. Click Stop and you can stop playing.
I hope this article will help you with your Android program.