android 四大组件service 音乐播放器的实现

来源:互联网 发布:sqlserver修改主键值 编辑:程序博客网 时间:2024/06/04 22:46
  • 新创建一个Android工程《音乐播放器》,包名:com.itheima.musicPlayer。
    在res目录下新建一个文件夹raw(名字必须为raw,约定大于配置的原则),然后在raw目录中拷贝进一个音乐文件,注意文件名必须遵循Android资源文件的命名规则。
  • 在src目录下,新建一个MediaService继承Service类,在该类中实现核心服务的方法。
private static MediaPlayer player;    public static  int ispb;    @Override    public IBinder onBind(Intent intent) {        System.out.println("服务返回了MediaContoller对象。。。。");        return  new MediaContoller();    }    @Override    public void onCreate() {        super.onCreate();        System.out.println("创建一个服务,并初始化MediaPlayer");        player = MediaPlayer.create(getApplicationContext(), R.raw.a);    }    public static class MediaContoller extends Binder{        //开始播放        public int play(){            player.start();            return 0;        }        //暂停播放        public int  puse(){            player.pause();            return 1;        }        //停止播放        public void stop(){            player.stop();        }        //音乐的总时长        public int getDuration(){            return player.getDuration();        }        //当前播放的位置        public int getCurrentPosition(){            return player.getCurrentPosition();        }        //判断是否播放        public boolean isplaying(){            return player.isPlaying();        }    }
  • 这是使用系统默认的布局文件,activity_main.xml
<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" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:padding="10dp"        android:text="音乐播放器"        android:textSize="20sp" />    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal" >        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_weight="1"            android:onClick="play"            android:text="播放" />        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_weight="1"            android:onClick="puse"            android:text="暂停" />        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_weight="1"            android:onClick="stop"            android:text="停止" />    </LinearLayout>    <ProgressBar        android:id="@+id/pb"        style="?android:attr/progressBarStyleHorizontal"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:paddingTop="10dp" /></LinearLayout>
  • 使用默认的MainActivity类,在该类中完成业务的控制
package com.example.servicemusic;import com.example.service.MusicService;import com.example.service.MusicService.MediaContoller;import android.support.v7.app.ActionBarActivity;import android.annotation.SuppressLint;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.os.SystemClock;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.MediaController;import android.widget.ProgressBar;import android.widget.Toast;public class MainActivity extends ActionBarActivity {    private ProgressBar pb;    // 声明自定义的MediaController对象    private MediaContoller controller;    private boolean isrunning;    private static int ispb;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        pb = (ProgressBar) findViewById(R.id.pb);        // 如何绑定服务?        // 创建一个用于启动服务的显示意图,指向我们自定义的MediaService类        Intent service = new Intent(this, MusicService.class);        // 绑定服务,同时服务开启,如果成功则返回true否则返回false        isrunning = bindService(service, new MediaConnection(),                BIND_AUTO_CREATE);        if (isrunning) {            System.out.println("服务绑定成功!");        } else {            System.out.println("服务绑定失败!");        }    }    /**     * 播放     *      * @param v     */    @SuppressLint("ShowToast")    public void play(View v) {        if (controller != null) {            if (controller.isplaying()) {                Toast.makeText(this, "音乐正在播放中......", 1).show();                return;            }else{                controller.play();                System.out.println("开始播放音乐");            }        }    }    /**     * 暂停     *      * @param v     */    public void puse(View v) {        if (controller != null) {            controller.puse();            System.out.println("音乐暂停");        }    }    /**     * 停止     *      * @param v     */    public void stop(View v) {        if (controller != null) {            pb.setProgress(0);            controller.stop();            //unbindService(new MediaConnection());//终止绑定            System.out.println("音乐停止");        }    }    /**     * 更新进度条     */    private void updatePro() {        new Thread() {            public void run() {                while (true) {                    SystemClock.sleep(400);                    pb.setProgress(controller.getCurrentPosition());                    if (controller.getCurrentPosition() == controller                            .getDuration()) {                        break;                    }                }            };        }.start();    }    /**     * 实现ServiceConnection 类     *      * @author Blake     *      */    class MediaConnection implements ServiceConnection {        /**         * 当service被绑定的时候回调该函数         */        @Override        public void onServiceConnected(ComponentName name, IBinder service) {            // 返回的ibinder对象其实就是我们自定义的MediaContoller            controller = (MediaContoller) service;            // 设置进度条的最大值            pb.setMax(controller.getDuration());            // 更新进度条            updatePro();            System.out.println("服务器已经连接......");        }        /**         * 服务器断开或关闭的时候调用该方法         */        @Override        public void onServiceDisconnected(ComponentName name) {            System.out.println("服务器断开或关闭");        }    }}
  • 在AndroidManifest.xml中注册Service
  • 将工程部署到模拟器上,点击播放,发现成功播放了音乐。点击暂停,发现音乐暂停了,然后点击播放,音乐再次响起。点击停止,问题来了,我们发现点击停止后再次点击播放音乐没能再次播放,因为这里面直接调用MediaPlayer的stop方法是有bug的。因此为了解决这样的问题,我们应该将停止调用层pause方法,同时只需调用MediaPlayer的seekTo(int)方法将音乐设置到开始位置。
  • //停止播放
    public void stop(){
    player.pause();
    player.seekTo(0);
    }

    这里写图片描述
0 0
原创粉丝点击