开发流程:
A,创建服务把想使用的方法暴露出来。
B,定义接口,bind调用时返回对象,在service 开启播放音乐实时更新进度条的位置
C,Activity 中创建hander 更新UI
【1】布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click1"
android:text="播放" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click2"
android:text="暂停" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click3"
android:text="继续播放" />
<SeekBar
android:id="@+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
【2】创建接口
interface Iservice {
//把想暴露的方法定义在接口里
public void callplayMusic();
public void callpauseMusic();
public void callrePlayMusic();
public void callplaySeekToPosition(int position);
}
【3】创建Service
A,onCredte 方法中是用MediaPlayer
B,为了调用Service 里面方法 Bind开启服务,提供Binder 对象 调用里面方法
C,定义方法,使用Binder的子类暴露出去。
public class MusicService extends Service {
private Timer timer;
private TimerTask task;
private MediaPlayer mediaPlayer;
//[2]把我们定义的中间人对象返回
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
@Override
public void onCreate() {
//[1]播放sd卡里面的小苹果音乐
mediaPlayer = new MediaPlayer();
super.onCreate();
}
// 播放音乐的方法
public void playMusic() {
try {

本文介绍了如何在Android中开发后台音乐播放功能。通过创建服务并暴露关键方法,结合接口和Binder实现Activity与Service的交互,实现实时更新进度条。在Service中使用MediaPlayer,并在onCreate方法中初始化,然后通过bindService连接并调用服务内的播放控制方法。
1367

被折叠的 条评论
为什么被折叠?



