Android利用SeekBar实现简单音乐播放器
程序员文章站
2023-12-11 20:51:10
一.demo简介
利用aidl为activity绑定服务,利用handler机制,发送消息更新seekbar的ui,利用计时器定时更新seekbar的进度...
一.demo简介
利用aidl为activity绑定服务,利用handler机制,发送消息更新seekbar的ui,利用计时器定时更新seekbar的进度。实现对音乐的开始播放,到暂停,继续,以及停止播放的功能。以及实现拖动进度条播放音乐的功能。
二.aidl接口
利用aidl机制提供给mainactivity访问mymusicservice的方法,实现播放暂停等功能。
三.主要类代码
1.mymusicservice
package my.com.mymusicp; import android.app.service; import android.content.intent; import android.media.mediaplayer; import android.os.bundle; import android.os.ibinder; import android.os.message; import android.os.remoteexception; import android.support.annotation.nullable; import android.util.log; import java.io.ioexception; import java.util.timer; import java.util.timertask; /** * created by c_ljf on 16-12-26. */ public class mymusicservice extends service { private string tag="mymusicservice"; private mediaplayer mediaplayer; @override public void oncreate() { super.oncreate(); mediaplayer = new mediaplayer(); } @nullable @override public ibinder onbind(intent intent) { return new mymusicbinder(); } class mymusicbinder extends imymusicservice.stub{ @override public void play() throws remoteexception { playmusic(); } @override public void pause() throws remoteexception { pausemusic(); } @override public void stop() throws remoteexception { stopmusic(); } @override public void continueplay() throws remoteexception { replaymusic(); } @override public void seekplayprogress(int position) throws remoteexception { seekplaypositiom(position); } } //播放音乐 public void playmusic(){ mediaplayer.reset(); string url = "sdcard/music/fade.mp3"; log.i(tag,url); try { mediaplayer.setdatasource(url); mediaplayer.prepare(); } catch (ioexception e) { e.printstacktrace(); } // might take long! (for buffering, etc) mediaplayer.start(); //更新播放进度条 seekplayprogress(); } public void pausemusic(){ mediaplayer.pause(); log.i(tag,"暂停播放"); } public void stopmusic(){ mediaplayer.reset(); log.i(tag,"停止播放"); mediaplayer.stop(); } @override public void ondestroy() { super.ondestroy(); } public void seekplaypositiom(int positon){ log.i(tag,"设置播放位置"); mediaplayer.seekto(positon); } public void seekplayprogress(){ /*1.获取当前歌曲的总时长*/ final int duration=mediaplayer.getduration(); //计时器对象 final timer timer=new timer(); final timertask task=new timertask() { @override public void run() { //开启线程定时获取当前播放进度 int currentposition=mediaplayer.getcurrentposition(); //利用message给主线程发消息更新seekbar进度 message ms=message.obtain(); bundle bundle=new bundle(); bundle.putint("duration",duration); log.i(tag,"歌曲总长度"+duration); bundle.putint("currentposition",currentposition); log.i(tag,"当前长度"+currentposition); //设置发送的消息内容 ms.setdata(bundle); //发送消息 mainactivity.handler.sendmessage(ms); } }; timer.schedule(task,300,500); //当播放结束时停止播放 mediaplayer.setoncompletionlistener(new mediaplayer.oncompletionlistener() { @override public void oncompletion(mediaplayer mp) { log.i(tag,"取消计时任务"); timer.cancel(); task.cancel(); } }); } public void replaymusic() { log.i(tag, "继续播放音乐"); mediaplayer.start(); } }
2.mainactivity
package my.com.mymusicp; import android.manifest; import android.app.activity; import android.content.componentname; import android.content.intent; import android.content.serviceconnection; import android.content.pm.packagemanager; import android.os.bundle; import android.os.handler; import android.os.ibinder; import android.os.message; import android.os.remoteexception; import android.support.v4.app.activitycompat; import android.support.v7.app.appcompatactivity; import android.view.view; import android.widget.button; import android.widget.seekbar; public class mainactivity extends appcompatactivity { private imymusicservice imymusicservice; private static seekbar seekbar; private button btpause_play; private boolean b=true;//判断暂停和继续播放 public static handler handler=new handler(){ @override public void handlemessage(message msg) { //处理消息 bundle bundle=msg.getdata(); //获取歌曲长度和当前播放位置,并设置到进度条上 int duration=bundle.getint("duration"); int currentposition=bundle.getint("currentposition"); seekbar.setmax(duration); seekbar.setprogress(currentposition); } }; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); verifystoragepermissions(mainactivity.this); //获取播放暂停按钮 btpause_play=(button) findviewbyid(r.id.bt_pause); intent intent=new intent(mainactivity.this,mymusicservice.class); bindservice(intent,new myconn(),bind_auto_create); seekbar=(seekbar) findviewbyid(r.id.seekbar); seekbar.setonseekbarchangelistener(new seekbar.onseekbarchangelistener() { @override public void onprogresschanged(seekbar seekbar, int progress, boolean fromuser) { } @override public void onstarttrackingtouch(seekbar seekbar) { } @override public void onstoptrackingtouch(seekbar seekbar) { try { imymusicservice.seekplayprogress(seekbar.getprogress()); } catch (remoteexception e) { e.printstacktrace(); } } }); } //定义服务连接类 class myconn implements serviceconnection{ @override public void onserviceconnected(componentname name, ibinder service) { imymusicservice=imymusicservice.stub.asinterface(service); } @override public void onservicedisconnected(componentname name) { } } public void play(view v){ try { imymusicservice.play(); } catch (remoteexception e) { e.printstacktrace(); } } public void pause(view v){ try { if(b) { imymusicservice.pause(); b=false; btpause_play.settext("继续播放"); } else{ b=true; imymusicservice.continueplay(); btpause_play.settext("暂停播放"); } } catch (remoteexception e) { e.printstacktrace(); } } public void stop(view v){ try { imymusicservice.stop(); } catch (remoteexception e) { e.printstacktrace(); } } // storage permissions private static final int request_external_storage = 1; private static string[] permissions_storage = { manifest.permission.read_external_storage, manifest.permission.write_external_storage, }; /** * checks if the app has permission to write to device storage * * if the app does not has permission then the user will be prompted to grant permissions * * @param activity */ public static void verifystoragepermissions(activity activity) { // check if we have write permission int permission = activitycompat.checkselfpermission(activity, manifest.permission.write_external_storage); if (permission != packagemanager.permission_granted) { // we don't have permission so prompt the user activitycompat.requestpermissions( activity, permissions_storage, request_external_storage ); } } }
四.布局文件
<?xml version="1.0" encoding="utf-8"?> <relativelayout 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:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" android:paddingbottom="@dimen/activity_vertical_margin" tools:context="my.com.mymusicp.mainactivity"> <linearlayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignparenttop="true" android:layout_alignparentleft="true" android:layout_alignparentstart="true" android:id="@+id/linearlayout"> <button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="开始播放" android:onclick="play" android:id="@+id/bt_start"/> <button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="暂停播放" android:layout_weight="1" android:onclick="pause" android:id="@+id/bt_pause"/> <button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="停止播放" android:onclick="stop" android:id="@+id/bt_stop"/> </linearlayout> <seekbar android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/seekbar" android:layout_below="@+id/linearlayout" android:layout_alignparentleft="true" android:layout_alignparentstart="true"/> </relativelayout>
五.注册服务
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="my.com.mymusicp"> <uses-permission android:name="android.permission.read_external_storage"/> <uses-permission android:name="android.permission.write_external_storage"/> <application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsrtl="true" android:theme="@style/apptheme"> <activity android:name=".mainactivity"> <intent-filter> <action android:name="android.intent.action.main"/> <category android:name="android.intent.category.launcher"/> </intent-filter> </activity> <service android:name=".mymusicservice"/> </application> </manifest>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。