ANDROID_MARS学习笔记_S01原始版_023_MP3PLAYER005_用广播BroacastReciever实现后台播放不更新歌词
一、代码流程
1.自定义一个AppConstant.LRC_MESSAGE_ACTION字符串表示广播"更新歌词"
2.在PlayerActivity的onResume()注册BroadcastReceiver,在onPause解除BroadcastReceiver
3.自定义LrcMessageBroadcastReceiver继承BroadcastReceiver,在onCreate()通过intent获取歌词,更新UI
4.所有更新歌词的操作移到PlayerService中
二、代码
1.xml
2.java
(1)PlayerActivity.java
package tony.mp3player; import tony.model.Mp3Info;
import tony.mp3player.service.PlayerService;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView; //更新歌词的工作不再在activity中完成,Activity只被动地接收service的广播以更新歌词,
//原来的相关歌词操作挪到service中完成
public class PlayerActivity extends Activity { private ImageButton beginBtn = null;
private ImageButton pauseBtn = null;
private ImageButton stopBtn = null; private TextView lrcTextView = null;
private Mp3Info info = null; private IntentFilter intentFilter = null;
private BroadcastReceiver receiver = null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
Intent intent = getIntent();
info = (Mp3Info) intent.getSerializableExtra("mp3Info");
beginBtn = (ImageButton) findViewById(R.id.begin);
pauseBtn = (ImageButton) findViewById(R.id.pause);
stopBtn = (ImageButton) findViewById(R.id.stop);
lrcTextView = (TextView) findViewById(R.id.lrcText); beginBtn.setOnClickListener(new BeginListener());
pauseBtn.setOnClickListener(new PauseListener());
stopBtn.setOnClickListener(new StopListener());
} @Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
} @Override
protected void onResume() {
super.onResume();
receiver = new LrcMessageBroadcastReceiver();
registerReceiver(receiver, getIntentFilter());
} private IntentFilter getIntentFilter() {
if(intentFilter == null) {
intentFilter = new IntentFilter();
intentFilter.addAction(AppConstant.LRC_MESSAGE_ACTION);
}
return intentFilter;
} /**
* 广播接收器,主要接收service放送的广播,并且更新UI,也就是放置歌词 的textview
* @author T
*
*/
class LrcMessageBroadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String lrcMessage = intent.getStringExtra("lrcMessage");
lrcTextView.setText(lrcMessage);
}
} class BeginListener implements OnClickListener {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("mp3Info", info);
intent.putExtra("MSG", AppConstant.PlayerMsg.PLAY_MSG);
intent.setClass(PlayerActivity2.this, PlayerService.class);
startService(intent);
}
} class PauseListener implements OnClickListener {
@Override
public void onClick(View v) {
//通知Service暂停播放MP3
Intent intent = new Intent();
intent.putExtra("MSG", AppConstant.PlayerMsg.PAUSE_MSG);
intent.setClass(PlayerActivity2.this, PlayerService.class);
startService(intent);
}
} class StopListener implements OnClickListener {
@Override
public void onClick(View v) {
//通知Service停止播放MP3文件
Intent intent = new Intent();
intent.putExtra("MSG", AppConstant.PlayerMsg.STOP_MSG);
intent.setClass(PlayerActivity2.this, PlayerService.class);
startService(intent);
}
}
}
(2)PlayerService.java
package tony.mp3player.service; import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Queue; import tony.model.Mp3Info;
import tony.mp3player.AppConstant;
import tony.mp3player.LrcProcessor;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder; public class PlayerService extends Service { private boolean isPlaying = false;
private boolean isPause = false;
private boolean isReleased = false;
private MediaPlayer mediaPlayer = null; private Mp3Info info = null;
private List<Queue> queues = null;
private Handler handler = new Handler();
private UpdateTimeCallback updateTimeCallback = null;
private long begin = 0;
private long nextTimeMill = 0;
private long currentTimeMill = 0;
private String msg = null;
private long pauseTimeMills = 0; @Override
public IBinder onBind(Intent intent) {
return null;
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
info = (Mp3Info) intent.getSerializableExtra("mp3Info");
int MSG = intent.getIntExtra("MSG", 0);
if(info != null) {
if(MSG == AppConstant.PlayerMsg.PLAY_MSG) {
play(info);
}
} else {
if(MSG == AppConstant.PlayerMsg.PAUSE_MSG) {
pause();
}
else if(MSG == AppConstant.PlayerMsg.STOP_MSG) {
stop();
}
}
return super.onStartCommand(intent, flags, startId);
} /**
* 根据歌词文件的名字,来读取歌词文件当中的信息
* @param lrcName
*/
private void prepareLrc(String lrcName) {
try {
InputStream inputStream;
inputStream = new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator + "mp3" + File.separator + info.getLrcName());
LrcProcessor lrcProcessor = new LrcProcessor();
queues = lrcProcessor.process(inputStream);
updateTimeCallback = new UpdateTimeCallback(queues);
begin = 0;
currentTimeMill = 0;
nextTimeMill = 0;
} catch (Exception e) {
e.printStackTrace();
}
} class UpdateTimeCallback implements Runnable{
Queue<Long> times = null;
Queue<String> msgs = null; public UpdateTimeCallback(List<Queue> queues) {
this.times = queues.get(0);
this.msgs = queues.get(1);
} @Override
public void run() {
//计算偏移量,也就是说从开始播放MP3到现在为止,共消耗了多少时间,以毫秒为单位
long offset = System.currentTimeMillis() - begin;
if(currentTimeMill == 0) {//刚开始播放时,调用prepareLrc(),在其中设置currentTimeMill=0
nextTimeMill = times.poll();
msg = msgs.poll();
}
//歌词的显示是如下:例如
//[00:01.00]Look
//[00:03.00]Up
//[00:06.00]Down
//则在第1~3秒间是显示“look”,在第3~6秒间是显示"Up",在第6秒到下一个时间点显示"Down"
if(offset >= nextTimeMill) {
//发送广播,把此刻应该显示的歌词传出去
Intent intent = new Intent();
intent.setAction(AppConstant.LRC_MESSAGE_ACTION);
intent.putExtra("lrcMessage", msg);
sendBroadcast(intent);
msg = msgs.poll();
nextTimeMill = times.poll();
}
currentTimeMill = currentTimeMill + 100;
//在run方法里调用postDelayed,则会形成循环,每0.01秒执行一次线程
handler.postDelayed(updateTimeCallback, 100);
}
} private void play(Mp3Info info) {
if(!isPlaying) {
String path = getMp3Path(info);
mediaPlayer = MediaPlayer.create(this, Uri.parse("file://" + path));
mediaPlayer.setLooping(false);
mediaPlayer.start();
isPlaying = true;
isReleased = false; prepareLrc(info.getLrcName());
handler.postDelayed(updateTimeCallback, 5);
begin = System.currentTimeMillis();
}
} private void pause() {
if(mediaPlayer != null) {
if(!isReleased){
if(!isPause) {
mediaPlayer.pause();
//不再更新歌词
handler.removeCallbacks(updateTimeCallback);
//用来下面代码计算暂停了多久
pauseTimeMills = System.currentTimeMillis();
} else {
mediaPlayer.start();
handler.postDelayed(updateTimeCallback, 5);
//因为下面的时间偏移是这样计算的offset = System.currentTimeMillis() - begin;
//所以要把暂停的时间加到begin里去,
begin = System.currentTimeMillis() - pauseTimeMills + begin;
}
isPause = !isPause;
isPlaying = !isPlaying;
}
}
} private void stop() {
if(mediaPlayer != null) {
if(isPlaying) {
if(!isReleased) {
//从Handler当中移除updateTimeCallback
handler.removeCallbacks(updateTimeCallback);
mediaPlayer.stop();
mediaPlayer.release();
isReleased = true;
isPlaying = false;
}
}
}
} private String getMp3Path(Mp3Info mp3Info) {
String SDCardRoot = Environment.getExternalStorageDirectory()
.getAbsolutePath();
String path = SDCardRoot + File.separator + "mp3" + File.separator
+ mp3Info.getMp3Name();
return path;
}
}
ANDROID_MARS学习笔记_S01原始版_023_MP3PLAYER005_用广播BroacastReciever实现后台播放不更新歌词的更多相关文章
- ANDROID_MARS学习笔记_S01原始版_005_RadioGroup\CheckBox\Toast
一.代码 1.xml(1)radio.xml <?xml version="1.0" encoding="utf-8"?> <LinearLa ...
- ANDROID_MARS学习笔记_S01原始版_004_TableLayout
1.xml <?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android ...
- ANDROID_MARS学习笔记_S01原始版_003_对话框
1.AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest ...
- ANDROID_MARS学习笔记_S01原始版_002_实现计算乘积及menu应用
一.代码 1.xml(1)activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk ...
- ANDROID_MARS学习笔记_S01原始版_001_Intent
一.Intent简介 二.代码 1.activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.co ...
- ANDROID_MARS学习笔记_S01原始版_023_MP3PLAYER004_同步显示歌词
一.流程分析 1.点击播放按钮,会根据lrc名调用LrcProcessor的process()分析歌词文件,得到时间队列和歌词队列 2.new一个hander,把时间队列和歌词队列传给自定义的线程类U ...
- ANDROID_MARS学习笔记_S01原始版_023_MP3PLAYER003_播放mp3
一.简介 1.在onListItemClick中实现点击条目时,跳转到PlayerActivity,mp3info通过Intent传给PlayerActivity 2.PlayerActivity通过 ...
- ANDROID_MARS学习笔记_S01原始版_022_MP3PLAYER002_本地及remote标签
一.简介 1.在main.xml中用TabHost.TabWidget.FrameLayout标签作布局 2.在MainActivity中生成TabHost.TabSpec,调用setIndicato ...
- ANDROID_MARS学习笔记_S01原始版_021_MP3PLAYER001_下载mp3文件
一.简介 1.在onListItemClick()中new Intent,Intent以存储序列化后的mp2Info对象作为参数,启动serivce 2.DownloadService在onStart ...
随机推荐
- SQL SERVER 锁定的实例
---实例DB:AdventureWorks2014 --- 创建view DBLocks USE [AdventureWorks2014] GO /****** Object: View [dbo] ...
- 日志记录类LogHelper
开源日志log4net使用起来很方便,但是项目中不让用,所以自己重写了一个类,用来记录日志,比较简单. 1.首先是可以把日志分成多个类型,分别记录到不同的文件中 /// <summary> ...
- oracle 表空间常用语句
–查询表空间使用情况 SELECT UPPER(F.TABLESPACE_NAME) "表空间名", D.TOT_GROOTTE_MB "表空间大小(M)", ...
- eclipse项目文件编码格式和项目不一致的修改方法
eclipse导入了一个项目,并把其属性设置成了UTF-8,但是打开里面的文档之后,发现还是乱码,看了下属性,发现文档竟然还是GBK的编码 于是就百度了下,发现了解决方法,现在和大家分享下,希望能帮到 ...
- 2) LINQ编程技术内幕--yield return
yield return 使用.NET的状态机生成器 yield return关键词组自动实现IDisposable,使用这个可枚举的地方, 还存在一个隐含的try finally块. 示例代码: c ...
- hibernate案例 测试代码
测试staff数据表连接到maeclipse 在staff中插入一行 package com.hibernate.test; import org.hibernate.Session; import ...
- 【制作镜像Win*】系统配置
向livibirt.xml插入Line 6-13所示代码,即加入两个virtio-serial设备: <!--vnc方式登录,端口号自动分配,自动加1,可以通过virsh vncdisplay来 ...
- C语言中的%0nd,%nd,%-nd
C语言中的%0nd printf --> formatted print/格式化输出 一.十进制 d -> decimal/十(shí)进制 int a=1; int b=1234; do ...
- mysql学习笔记5
phpmyadmin中向数据表中插入新数据 INSERT INTO tb_admin(`table_id`, `table_name`, `table_des`, `table_time`) VAL ...
- wamp下开启SSL,解决APACHE启动问题
wamp开启SSL解决wamp5_1.7.4中APACHE启动问题 1.#修改httpd.conf文件LoadModule ssl_module modules/mod_ssl.soInclude c ...