使用服务,即Service就可以满足你的要求。
给你我以前自己写的示例:
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import com.hs.leozheng.phonelinkhs.MusicListActivity;
import com.hs.leozheng.phonelinkhs.AudioMediaInfo;
import com.hs.leozheng.phonelinkhs.AppConstant;
/***
* leo
* 音乐播放服务
*/
@SuppressLint("NewApi")
public class PlayerService extends Service {
private MediaPlayer mediaPlayer; // 媒体播放器对象
private String path; // 音乐文件路径
private int msg;
private boolean isPause; // 暂停状态
private int current = 0; // 记录当前正在播放的音乐
private List<AudioMediaInfo> mp3Infos; // 存放 AudioMediaInfo 对象的集合
private int status = 3; // 播放状态,默认为顺序播放
private MyReceiver myReceiver; // 自定义广播接收器
private int currentTime; // 当前播放进度
private int duration; // 播放长度
/**
* handler 用来接收消息,来发送广播更新播放时间
*/
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {
if(mediaPlayer != null) {
currentTime = mediaPlayer.getCurrentPosition(); // 获取当前音乐播放的位置
duration = mediaPlayer.getDuration();
Intent intent = new Intent();
intent.setAction(AppConstant.AUDIO_SEND_CURRENT);
intent.putExtra("currentTime", currentTime);
intent.putExtra("totalTime", duration);
sendBroadcast(intent); // 给 PlayerActivity 发送广播
handler.sendEmptyMessageDelayed(1, 100);
}
}
};
};
@Override
public void onCreate() {
super.onCreate();
Log.i("service", "service created");
mediaPlayer = new MediaPlayer();
mp3Infos = MusicListActivity.getMp3Infos(PlayerService.this);
myReceiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(AppConstant.AUDIO_CTRL_ACTION);
registerReceiver(myReceiver, filter);
/**
* 设置音乐播放完成时的监听器
*/
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
if (1 == status) { // 单曲循环
mediaPlayer.start();
} else if (2 == status) { // 全部循环
current++;
if(current > mp3Infos.size() - 1) { // 变为第一首的位置继续播放
current = 0;
}
path = mp3Infos.get(current).GetUrl();
Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);
sendIntent.putExtra("current", current);
sendIntent.putExtra("url", path);
sendIntent.putExtra("total", mp3Infos.size());
// 发送广播,将被 Activity 组件中的 BroadcastReceiver 接收到
sendBroadcast(sendIntent);
play(0);
} else if (3 == status) { // 顺序播放
current++; // 下一首位置
if (current <= mp3Infos.size() - 1) {
path = mp3Infos.get(current).GetUrl();
Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);
sendIntent.putExtra("current", current);
sendIntent.putExtra("url", path);
sendIntent.putExtra("total", mp3Infos.size());
sendBroadcast(sendIntent);
play(0);
}else {
mediaPlayer.seekTo(0);
current = 0;
path = mp3Infos.get(current).GetUrl();
Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);
sendIntent.putExtra("current", current);
sendIntent.putExtra("url", path);
sendIntent.putExtra("total", mp3Infos.size());
sendBroadcast(sendIntent);
}
} else if (4 == status) { // 随机播放
current = getRandomIndex(mp3Infos.size() - 1);
path = mp3Infos.get(current).GetUrl();
Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);
sendIntent.putExtra("current", current);
sendIntent.putExtra("url", path);
sendIntent.putExtra("total", mp3Infos.size());
sendBroadcast(sendIntent);
play(0);
}
}
});
}
/**
* 获取随机位置
*/
protected int getRandomIndex(int end) {
int index = (int) (Math.random() * end);
return index;
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startId) {
path = intent.getStringExtra("url"); // 歌曲路径
current = intent.getIntExtra("listPosition", -1); // 当前播放歌曲的在 mp3Infos 的位置
Log.i("Play Service", "onStart current is: " + Integer.toString(current));
msg = intent.getIntExtra("MSG", 0); // 播放信息
AppConstant.PlayerMsg msgEnum = AppConstant.PlayerMsg.values()[msg];
if (AppConstant.PlayerMsg.PLAY_MSG == msgEnum) { // 直接播放音乐
Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);
sendIntent.putExtra("current", current);
sendIntent.putExtra("url", path);
sendIntent.putExtra("total", mp3Infos.size());
// 发送广播,将被 Activity 组件中的 BroadcastReceiver 接收到
sendBroadcast(sendIntent);
play(0);
}
else if (AppConstant.PlayerMsg.PAUSE_MSG == msgEnum) { // 暂停
pause();
}
else if (AppConstant.PlayerMsg.STOP_MSG == msgEnum) { // 停止
stop();
}
else if (AppConstant.PlayerMsg.CONTINUE_MSG == msgEnum) { // 继续播放
resume();
}
else if (AppConstant.PlayerMsg.PRIVIOUS_MSG == msgEnum) { // 上一首
previous();
}
else if (AppConstant.PlayerMsg.NEXT_MSG == msgEnum) { // 下一首
next();
}
else if (AppConstant.PlayerMsg.PROGRESS_CHANGE == msgEnum) { // 进度更新
currentTime = intent.getIntExtra("progress", -1);
play(currentTime);
}
else if (AppConstant.PlayerMsg.PLAYING_MSG == msgEnum) {
handler.sendEmptyMessage(1);
}
super.onStart(intent, startId);
}
/**
* 播放音乐
*
* @param position
*/
private void play(int currentTime) {
try {
mediaPlayer.reset(); // 把各项参数恢复到初始状态
mediaPlayer.setDataSource(path);
Intent commonCtrl_intent = new Intent();
commonCtrl_intent.setAction(AppConstant.COMMON_UI_MSG);
commonCtrl_intent.putExtra("ACTION", "UIPlayingFilename");
// 对 URL 进行处理: 保显示文件名,不显示目录
int find = path.lastIndexOf('/') + 1;
String strFilename = null;
if(-1 != find)
{
strFilename = path.substring(find);
commonCtrl_intent.putExtra("filename", strFilename);
sendBroadcast(commonCtrl_intent);
}
mediaPlayer.prepare(); // 进行缓冲
mediaPlayer.setOnPreparedListener(new PreparedListener(currentTime)); // 注册一个监听器
handler.sendEmptyMessage(1);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 暂停音乐
*/
private void pause() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
isPause = true;
Intent commonCtrl_intent = new Intent();
commonCtrl_intent.setAction(AppConstant.COMMON_UI_MSG);
commonCtrl_intent.putExtra("ACTION", "UIPlayingStatus");
commonCtrl_intent.putExtra("playingStatus", 2);
sendBroadcast(commonCtrl_intent);
}
}
private void resume() {
if (isPause) {
mediaPlayer.start();
isPause = false;
Intent commonCtrl_intent = new Intent();
commonCtrl_intent.setAction(AppConstant.COMMON_UI_MSG);
commonCtrl_intent.putExtra("ACTION", "UIPlayingStatus");
commonCtrl_intent.putExtra("playingStatus", 1);
sendBroadcast(commonCtrl_intent);
}
}
/**
* 上一首
*/
private void previous() {
int size = mp3Infos.size();
if((current - 1) >= 0) {
current--;
}
else {
current = size - 1;
}
path = mp3Infos.get(current).GetUrl();
Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);
sendIntent.putExtra("current", current);
sendIntent.putExtra("url", path);
sendIntent.putExtra("total", size);
// 发送广播,将被 Activity 组件中的 BroadcastReceiver 接收到
sendBroadcast(sendIntent);
play(0);
}
/**
* 下一首
*/
private void next() {
int size = mp3Infos.size();
if((current + 1) <= (size - 1)) {
current++;
}
else {
current = 0;
}
path = mp3Infos.get(current).GetUrl();
Intent sendIntent = new Intent(AppConstant.AUDIO_SEND_UPDATE);
sendIntent.putExtra("current", current);
sendIntent.putExtra("url", path);
sendIntent.putExtra("total", size);
// 发送广播,将被 Activity 组件中的 BroadcastReceiver 接收到
sendBroadcast(sendIntent);
play(0);
}
/**
* 停止音乐
*/
private void stop() {
if (mediaPlayer != null) {
mediaPlayer.stop();
try {
mediaPlayer.prepare(); // 在调用 stop 后如果需要再次通过 start 进行播放,需要之前调用 prepare 函数
} catch (Exception e) {
e.printStackTrace();
}
Intent commonCtrl_intent = new Intent();
commonCtrl_intent.setAction(AppConstant.COMMON_UI_MSG);
commonCtrl_intent.putExtra("ACTION", "UIPlayingStatus");
commonCtrl_intent.putExtra("playingStatus", 3);
sendBroadcast(commonCtrl_intent);
}
}
@Override
public void onDestroy() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
/**
*
* 实现一个 OnPrepareLister 接口,当音乐准备好的时候开始播放
*
*/
private final class PreparedListener implements OnPreparedListener {
private int currentTime;
public PreparedListener(int currentTime) {
this.currentTime = currentTime;
}
@Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start(); // 开始播放
if (currentTime > 0) { // 如果音乐不是从头播放
mediaPlayer.seekTo(currentTime);
}
Intent intent = new Intent();
intent.setAction(AppConstant.AUDIO_SEND_DURATION);
duration = mediaPlayer.getDuration();
intent.putExtra("duration", duration); // 通过 Intent 来传递歌曲的总长度
sendBroadcast(intent);
}
}
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
AppConstant.PlayerMsg msgEnum = AppConstant.PlayerMsg.APP_CONSTANT_MAX;
String action = intent.getAction();
int msg = intent.getIntExtra("MSG", -1);
int mode = intent.getIntExtra("mode", 3);
if(msg > 0) {
msgEnum = AppConstant.PlayerMsg.values()[msg];
}
if(action.equals(AppConstant.AUDIO_CTRL_ACTION)) {
Log.v("Play Service", "Control: " + Integer.toString(msg));
if(msgEnum == AppConstant.PlayerMsg.PRIVIOUS_MSG)
{
Log.v("Play Service", "Control.Prev");
previous();
}
else if(msgEnum == AppConstant.PlayerMsg.NEXT_MSG)
{
Log.v("Play Service", "Control.Next");
next();
}
else if(msgEnum == AppConstant.PlayerMsg.PLAY_MODE)
{
Log.v("Play Service", "Control.Mode: " + Integer.toString(mode));
}
else if(msgEnum == AppConstant.PlayerMsg.CONTINUE_MSG)
{
Log.v("Play Service", "Control.Continue");
resume();
}
else if(msgEnum == AppConstant.PlayerMsg.PAUSE_MSG)
{
Log.v("Play Service", "Control.Pause");
pause();
}
}
}
}
}
调用 方式:
Intent intent = new Intent();
intent.putExtra("url", audioMediaInfo.GetUrl()); // 参数可要、可不要
intent.putExtra("listPosition", positionSelected/*getPlayingIndex(audioMediaInfo.GetUrl())*/);
intent.putExtra("MSG", AppConstant.PlayerMsg.PLAY_MSG.ordinal());
intent.setClass(MusicListActivity.this, PlayerService.class);
startService(intent);
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。