Service-based music player for Android Development
This is a Service-based music player. The program's music will be played by the background Service component. When the background playing status changes, the program sends a broadcast notification to the foreground Activity update interface. When you click the foreground Activity interface button or drag the progress bar, the system sends a broadcast notification to the background Service to change the playing status and play the specified music.
Program running:
Vc = ">
Program code:
Program Interface Class (MusicBox. java ):
Package com. jph. musicbox; import com. jph. util. constUtil; import android. OS. bundle; import android. app. activity; import android. app. alertDialog; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; import android. content. intentFilter; import android. view. layoutInflater; import android. view. menu; import android. view. menuItem; import android. view. view; import android. view. view. onClickListener; import android. widget. imageButton; import android. widget. linearLayout; import android. widget. seekBar; import android. widget. seekBar. onSeekBarChangeListener; import android. widget. textView;/*** Describe:
*
Service-based music broadcaster *
This application mainly implements :*
1. Send playback-related control information through the foreground Activity, in the form of broadcast *
The Service passed to the background. The background Service is responsible for playing music. *
It is also responsible for receiving background broadcasts to update the song and singer names on the playing interface. *
2. display the current playback position through the progress bar. When you drag the progress bar *
Use the OnSeekBarChangeListener event to control *
The mediaPlayer in the background plays music at the specified position. *
@ Author jph *
Date: 2014.08.07 **/public class MusicBox extends Activity {ImageButton btnPlayOrPause, btnPre, btnNext; // progress bar static SeekBar skbMusic; // obtain the title of the Song and text box TextView title of the author displayed on the page, author; String [] titleStrs = new String [] {"taosheng still", "Rape flower", "You Are The One "}; string [] authorStrs = new String [] {"Mao Ning", "Jackie Chan", "unknown artist"}; // specifies whether boolean isPlaying = false is being played; @ Overrideprotected void onCreate (Bundle savedInstanceState) {supe R. onCreate (savedInstanceState); setContentView (R. layout. main); skbMusic = (SeekBar) findViewById (R. id. skbMusic); skbMusic. setOnSeekBarChangeListener (sChangeListener); btnNext = (ImageButton) findViewById (R. id. btnNext); btnPlayOrPause = (ImageButton) findViewById (R. id. btnPlayOrPause); btnPre = (ImageButton) findViewById (R. id. btnPre); btnNext. setOnClickListener (listener); btnPlayOrPause. setOnClickListener (listener); btn Pre. setOnClickListener (listener); title = (TextView) findViewById (R. id. title); author = (TextView) findViewById (R. id. author); title. setText (titleStrs [0]); author. setText (authorStrs [0]); // register the receiver MusicBoxReceiver mReceiver = new MusicBoxReceiver (); IntentFilter filter = new IntentFilter (); filter. addAction (ConstUtil. MUSICBOX_ACTION); registerReceiver (mReceiver, filter); // start the backend ServiceIntent intent = new Intent (this, Musi CService. class); startService (intent);} OnClickListener listener = new OnClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubswitch (v. getId () {case R. id. btnNext: // The next btnPlayOrPause. setBackgroundResource (R. drawable. state_pasue); sendBroadcastToService (ConstUtil. STATE_NEXT); isPlaying = true; break; case R. id. btnPlayOrPause: // play or pause if (! IsPlaying) {btnPlayOrPause. setBackgroundResource (R. drawable. state_pasue); sendBroadcastToService (ConstUtil. STATE_PLAY); isPlaying = true;} else {btnPlayOrPause. setBackgroundResource (R. drawable. state_play); sendBroadcastToService (ConstUtil. STATE_PAUSE); isPlaying = false;} break; case R. id. btnPre: // The Last btnPlayOrPause. setBackgroundResource (R. drawable. state_pasue); sendBroadcastToService (ConstUtil. STATE_PREVIOUS); isPlaying = true; break; default: break ;}};/*** SeekBar progress change event */OnSeekBarChangeListener sChangeListener = new OnSeekBarChangeListener () {@ Overridepublic void onStopTrackingTouch (SeekBar seekBar) {// TODO Auto-generated method stub // After the drag is stopped, control the mediaPlayer to play music MusicService at the specified position. mediaPlayer. seekTo (seekBar. getProgress (); MusicService. isChanging = false ;}@ Overridepublic void onStartTrackingTouch (SeekBar seekBar) {// TODO Auto-generated method stubMusicService. isChanging = true;} @ Overridepublic void onProgressChanged (SeekBar seekBar, int progress, boolean fromUser) {// TODO Auto-generated method stub}; @ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. menu. add (Menu. NONE, ConstUtil. MENU_ABOUT, Menu. NONE, "about"); menu. add (Menu. NONE, ConstUtil. MENU_EXIT, Menu. NONE, "exit"); return true;}/*** send control broadcast to backend Service * @ param state int state control status code **/protected void sendBroadcastToService (int state) {// TODO Auto-generated method stubIntent intent = new Intent (); intent. setAction (ConstUtil. MUSICSERVICE_ACTION); intent. putExtra ("control", state); // send the broadcast sendBroadcast (intent) ;}@ Overridepublic boolean onOptionsItemSelected (MenuItem item) of the playback control to the background Service) {// TODO Auto-generated method stubswitch (item. getItemId () {case ConstUtil. MENU_ABOUT: LayoutInflater inflater = LayoutInflater. from (this); LinearLayout layout = (LinearLayout) inflater. inflate (R. layout. about, null); AlertDialog dialog = new AlertDialog. builder (this ). create (); dialog. setTitle ("about"); dialog. setIcon (R. drawable. ic_launcher); dialog. setView (layout); dialog. show (); break; case ConstUtil. MENU_EXIT: sendBroadcastToService (ConstUtil. STATE_STOP); this. finish (); break; default: break;} return true ;} // create a broadcast receiver to receive the broadcast class MusicBoxReceiver extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, Intent intent) sent by the background Service) {// TODO Auto-generated method stub // gets the current message in the Intent. current indicates the currently playing song int current = intent. getIntExtra ("current",-1); title. setText (titleStrs [current]); // update the music Title author. setText (authorStrs [current]); // updated by music author }}}
Background services for music playback:
MusicService. java
Package com. jph. musicbox; import java. io. IOException; import java. util. timer; import java. util. timerTask; import com. jph. util. constUtil; import android. app. service; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; import android. content. intentFilter; import android. content. res. assetFileDescriptor; import android. content. res. assetManager; import android. media. mediaPlayer; import android. media. mediaPlayer. onCompletionListener; import android. OS. IBinder;/*** Describe:
*
Background Service responsible for music playback *
1. Play a specified music by receiving a broadcast from the foreground that controls the playback information *
2. Load the music in the assets Directory *
3. Create a listener for the mediaPlayer completion event when the current music is played *
Automatically play the next music *
4. Create a timer for each playing music to detect the playback progress *
And update the progress bar *
@ Author jph *
Date: 2014.08.07 **/public class MusicService extends Service {Timer mTimer; TimerTask mTimerTask; static boolean isChanging = false; // mutex variable, prevent degree conflict between the timer and SeekBar when dragging // create a media player object static MediaPlayer mediaPlayer; // create an Asset manager object AssetManager assetManager; // array of music names String [] musics = new String [] {"taoshengyijiu-maoning.mp3", "youcaihua-chenglong.mp3", "You Are The onenames "}; // The current playing music int current = 0; // The current playing status int s Tate = ConstUtil. STATE_NON; // record the Timer running status boolean isTimerRunning = false; @ Overridepublic void onCreate () {// TODO Auto-generated method stubsuper. onCreate (); // register the receiver MusicSercieReceiver receiver = new MusicSercieReceiver (); IntentFilter filter = new IntentFilter (); filter. addAction (ConstUtil. MUSICSERVICE_ACTION); registerReceiver (receiver, filter); mediaPlayer = new MediaPlayer (); assetManager = getAssets (); // mediaPl The completion event of ayer creates the listener mediaPlayer. setOnCompletionListener (new OnCompletionListener () {@ Overridepublic void onCompletion (MediaPlayer mp) {// TODO Auto-generated method stub // mTimer. cancel (); // cancel the timer current ++; prepareAndPlay (current );}});} /*** load and play music ** @ param index int index the index of the first music to play **/protected void prepareAndPlay (int index) {// TODO Auto-generated method stubif (isTimerRunning) {// If Timer is running mTimer. ca Ncel (); // cancel the timer isTimerRunning = false;} if (index> 2) {current = index = 0;} if (index <0) {current = index = 2;} // send broadcast stop foreground Activity update interface Intent intent = new Intent (); intent. putExtra ("current", index); intent. setAction (ConstUtil. MUSICBOX_ACTION); sendBroadcast (intent); try {// obtain the AssetFileDescriptor object AssetFileDescriptor assetFileDescriptor AssetFileDescriptor = assetManager of the specified file in the assets Directory. openFd (musics [current]); mediaPlayer. reset (); // initialize mediaPl Ayer object mediaPlayer. setDataSource (assetFileDescriptor. getFileDescriptor (), assetFileDescriptor. getStartOffset (), assetFileDescriptor. getLength (); // prepare to play the music mediaPlayer. prepare (); // play the music mediaPlayer. start (); // The getDuration () method must be followed by the prepare () method. Otherwise, the Attempt to call getDuration without a valid mediaplayer exception MusicBox will occur. skbMusic. setMax (mediaPlayer. getDuration (); // set the SeekBar length} catch (IOException e) {// TODO Auto- Generated catch blocke. printStackTrace ();} // ---------- the Timer records the playback progress --------- // mTimer = new Timer (); mTimerTask = new TimerTask () {@ Override public void run () {isTimerRunning = true; if (isChanging = true) // when the user is dragging the progress bar, return of the progress bar is not processed; MusicBox. skbMusic. setProgress (mediaPlayer. getCurrentPosition () ;}}; // checks the playback progress of mTimer every 10 milliseconds. schedule (mTimerTask, 0, 10) ;}@ Overridepublic IBinder onBind (Intent inten T) {// TODO Auto-generated method stubreturn null;} // create a broadcast receiver to receive the broadcast class MusicSercieReceiver extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, intent intent) {// TODO Auto-generated method stubint control = intent. getIntExtra ("control",-1); switch (control) {case ConstUtil. STATE_PLAY: // play the music if (state = ConstUtil. STATE_PAUSE) {// if the original status is paused mediaPlayer. start ();} else if (State! = ConstUtil. STATE_PLAY) {prepareAndPlay (current);} state = ConstUtil. STATE_PLAY; break; case ConstUtil. STATE_PAUSE: // pause if (state = ConstUtil. STATE_PLAY) {mediaPlayer. pause (); state = ConstUtil. STATE_PAUSE;} break; case ConstUtil. STATE_STOP: // stop playing if (state = ConstUtil. STATE_PLAY | state = ConstUtil. STATE_PAUSE) {mediaPlayer. stop (); state = ConstUtil. STATE_STOP;} break; case ConstUtil. STATE_PREVIOUS: // prepareAndPlay (-- current); state = ConstUtil. STATE_PLAY; break; case ConstUtil. STATE_NEXT: // The next prepareAndPlay (++ current); state = ConstUtil. STATE_PLAY; break; default: break ;}}}}
Constant tool class (ConstUtil. java ):
Package com. jph. util;/*** Describe:
*
Constant tool class *
It is mainly used for constants used by other class providers *
@ Author jph *
Date: 2014.08.07 **/public class ConstUtil {// Actionpublic static final String MUSICBOX_ACTION = "com. jph. musicbox. MUSICBOX_ACTION "; // Actionpublic static final String MUSICSERVICE_ACTION =" com. jph. musicbox. MUSICSERVICE_ACTION "; // initialize flagpublic static final int STATE_NON = 0x122; // flagpublic static final int STATE_PLAY = 0x123; // pause the flagpublic static final int STATE_PAUSE = 0x124; // stop the flagpublic static final int STATE_STOP = 0x125; // flagpublic static final int STATE_PREVIOUS = 0x126; // flagpublic static final int STATE_NEXT = 0x127; // menu itemIdpublic static final int MENU_ABOUT = 0x200; // The itemIdpublic static final int MENU_EXIT = 0x201; public ConstUtil () {// TODO Auto-generated constructor stub }}
Configuration File: AndroidManifest. xml: