Android 后台播放音乐Demo

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

 

开发流程:

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 {

   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

兴帅_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值