Android—在Activity中绑定service播放音乐

摘要: 本文用来介绍在Activity中绑定一个服务(service),在服务中播放音乐的方法。相信看完之后会对绑定service有个直观的认识和掌握基本用法,先看代码,再看解释。
     
public class MusicService extends Service {

    private MediaPlayer mediaPlayer = new MediaPlayer();
    private final IBinder iBinder = new MusicBinder();



    public MusicService() {

    }



    /**
     * MusicBinder 提供了getService方法来获得当前MusicService的实例
     */
    public class  MusicBinder extends Binder{
          public MusicService getService(){
            return MusicService.this;
    }

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.


        return iBinder ;
    }
 
首先,自定义一个MusicService并继承Service类,然后在定义一个MusicBinder对象,这个对象是内部类并继承Binder类实现的,在类实现里面包含一个方法,此方法是用来返回当前这个Service对象用的,然后在重写的onBind方法中,返回这个MusicBinder对象。至此,MusicService部分就完成了,接下来看Activity中的实现。

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = new Intent(getActivity(),MusicService.class);
        getActivity().bindService(intent,connection,Context.BIND_AUTO_CREATE);//绑定播放音乐的服务



    }
在Activity中onCreate的方法中创建一个intent对象,表示要绑定到哪个服务中去,然后调用 bindService方法绑定MusicService服务(因为我这是在fragment中写的播放器,所以要用getActivity()方法来获得Activity,不然的话直接用bindService就行了),bindService的第一个参数是Intent,第二个参数是表示一个服务连接对象,第四个参数是表示自动创建服务,如果服务不存在就创建服务,否则不创建。

private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MusicService.MusicBinder binder = (MusicService.MusicBinder) service;
            musicService = binder.getService();
            playMusic(audioList.get(currentItem));
            bound=true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bound = false;
        }
    };
定义第二个参数的ServiceConnect对象,在里面重写它的方法onServiceConnected(),把参数IBinder转换成我们自定义的MusicBinder对象,再用 MusicBinder中的getService获得MusicService服务,并把它赋值给声明好的MusicService对象(musicService),这样就建立起了程序和服务之间的联系。

/**
     * 播放音乐的方法
     * @param currentPath  音乐文件路径
     */
    public void playMusic(String currentPath){

        try {
            if(mediaPlayer.isPlaying()){//如果当前正在播放音乐,则先停止
                mediaPlayer.stop();
            }
            mediaPlayer.reset();//重置播放器z状态
            mediaPlayer.setDataSource(currentPath);
            mediaPlayer.prepare();

            mediaPlayer.start();

           // updateSeekBar();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

然后在MusicService中写好播放音乐的playMusic()方法。

musicService.playMusic(currentPath);

在Activity中需要服务播放音乐时,就直接调用playMusic方法就行了,接下来介绍服务的解除绑定。
 @Override
    public void onDestroy() {
       

        if(bound){
            getActivity().unbindService(connection);
            bound = false;
        }

       
        super.onDestroy();
    }

在Activity中的onDestroy()方法中,判断是不是绑定了服务,判断是否绑定就设置一个全局的布尔类型bound就行了。如果绑定了就调用unbindService()方法解除绑定,解除绑定后根据绑定service的生命周期,它会被系统自动销毁。

至此,一个绑定service的方法法就完成了,本人菜B一枚,不正之处,还望指出,不甚感激!


你可能感兴趣的:(android学习)