安卓用服务做一个简单音乐播放器

xml文件



    
新建一个类MyMusicService.java

package com.example.musicplayerdemo;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;

public class MyMusicService extends Service {

	private MediaPlayer mediaPlayer;// = new MediaPlayer(); //媒体播放器对象
	private boolean isPause; // 暂停状态

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		mediaPlayer = MediaPlayer.create(this, R.raw.znq);// 此处引用到我们的mp3文件,raw文件夹的。
		Log.i("Msg", "create");

	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		int msg = intent.getIntExtra("MSG", 0);
		Log.i("Msg", msg + "");
		if (msg == 0) {
			play(0);
		} else if (msg == 1) {
			pause();
		} else if (msg == 2) {
			reset();
		} else if (msg == 3) {
			stop();
		}
		return super.onStartCommand(intent, flags, startId);
	}

	/**
	 * 播放音乐
	 * 
	 * @param position
	 */
	private void play(int position) {
		try {
			mediaPlayer.start(); // 开始播放
			if (position > 0) { // 如果音乐不是从头播放
				mediaPlayer.seekTo(position);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 暂停音乐
	 */
	private void pause() {
		if (mediaPlayer != null && mediaPlayer.isPlaying()) {
			mediaPlayer.pause();
			isPause = true;
		} else {
			if (isPause) {
				mediaPlayer.start();
				isPause = false;
			}
		}
	}

	/**
	 * 停止音乐
	 */
	private void reset() {
		if (mediaPlayer.isPlaying()) {
			mediaPlayer.seekTo(0);
		} else {
			play(0);
		}
	}

	/**
	 * 停止音乐
	 */
	private void stop() {
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			try {
				mediaPlayer.prepare(); // 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onDestroy() {
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			mediaPlayer.release();
		}
	}
	
}

Play.Activity

package com.example.musicplayerdemo;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class PlayActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_play);		
				
	}
	
	public void MediaPlay(View v) {
		switch (v.getId()) {
		case R.id.btnPlay:
			StartService(0);
			break;
		case R.id.btnPause:
			StartService(1);
			break;
		case R.id.btnRePlay:
			StartService(2);
			break;
		case R.id.btnStop:
			StartService(3);
			break;
		}
	}

	private void StartService(int flag) {
		Intent intent = new Intent();
		intent.putExtra("MSG", flag);
		intent.setClass(PlayActivity.this, MyMusicService.class);
		startService(intent);
	}

}



你可能感兴趣的:(Andrioid)