欢迎来到天天文库
浏览记录
ID:32165942
大小:46.75 KB
页数:3页
时间:2019-02-01
《黑马程序员安卓教程音乐播放器之编写服务》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、音乐播放器之编写服务在“音乐播放器之基本框架”中,我们已经编写了音乐播放器的页面实现,但具体的播放逻辑并没有实现。接下来,我们需要做的就是:响应ListView的条目点击事件,当点击某一个条目时开启服务,在该服务中播放选中的音乐。具体步骤如下:1.编写服务类在项目中新建一个类命名为:MusicService并使之继承Service。代码如例1-1所示:例1-1publicclassMusicServiceextendsService{@OverridepublicIBinderonBind(Int
2、entintent){returnnull;}}服务类创建出来之后,我们需要在项目清单文件中声明该服务。2.编写服务类中的方法在服务类MusicService中,我们要实现两个功能,分别是循环音乐的播放功能和当前所播放音乐是哪一首的功能。播放功能play方法代码如例1-2:例1-2publicvoidplay(finalListinfos,finalintposition){System.out.println("后台播放:"+infos.get(position).getP
3、ath());newThread(){publicvoidrun(){currentPostion=position;try{Thread.sleep(5000);//使当前线程是5秒,模拟音乐播放}catch(InterruptedExceptione){e.printStackTrace();}intnewposition=position+1;//播放下一首音乐的下标intpos=newposition%infos.size();currentPostion=pos;play(infos,p
4、os);//循环播放下一首音乐};}.start();}记录当前所播放哪一首音乐getCurrentPostion,代码如例1-3:例1-3publicintgetCurrentPostion(){returncurrentPostion;}在MusicService类中定义一个int类型的变量currentPostion,在方法play中更新currentPostion的值。1.编写中间人在服务MusicService中编写中间人内部类MyBinder,具体步骤如下:l编写接口类IMusicSe
5、rvice,在该类中定义两个方法。代码如例1-4所示:例1-4publicinterfaceIMusicService{publicvoidcallplay(finalListinfos,finalintposition);//播放音乐publicintcallGetCurrentPositon();//当前播放音乐时哪一首}lMusicService类中编写内部类MyBinder,使之继承Binder并实现IMusicService接口。代码如例1-5:例1-5privat
6、eclassMyBinderextendsBinderimplementsIMusicService{@Overridepublicvoidcallplay(Listinfos,intposition){play(infos,position);}@OverridepublicintcallGetCurrentPositon(){//TODOAuto-generatedmethodstubreturngetCurrentPostion();}}例1-5中MyBinder实现了
7、IMusicService接口,所以我们要在该类中重写接口类中所定义的方法。方法callplay实现了对服务类内部方法play的调用;方法callGetCurrentPositon实现了对服务类内部的方法getCurrentPostion调用。即实现了通过中间人来调用服务里面的方法。l实现服务类onBind方法,返回中间人对象。代码如例1-6:例1-6@OverridepublicIBinderonBind(Intentintent){//TODOAuto-generatedmethodstubr
8、eturnnewMyBinder();}
此文档下载收益归作者所有