package com.music.zds; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import android.os.Message; import android.util.Log; import java.util.Timer; import java.util.TimerTask; public class MusicService extends Service { public static final String TAG="MusicService"; public MediaPlayer player; private Timer timer; public MusicService() { Log.d(TAG,"MusicService"); } @Override public void onCreate() { super.onCreate(); player=new MediaPlayer(); } @Override public IBinder onBind(Intent intent) { Log.d(TAG,"MusicService()"); return new MusicControler(); } public void addTimer(){ if(timer ==null){ TimerTask task = new TimerTask() { @Override public void run() { if(player == null) return;; int duration = player.getDuration(); int currentPro = player.getCurrentPosition(); Log.w(TAG,"duration:"+duration+",progress:"+currentPro); Message msg = MainActivity.handler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putInt("duration",duration); bundle.putInt("progress",currentPro); msg.setData(bundle); MainActivity.handler.sendMessage(msg); } }; timer.schedule(task,5,500); } } class MusicControler extends Binder{ public void play(){ Log.d(TAG,"play"); try{ player.reset(); player=MediaPlayer.create(getApplicationContext(),R.raw.nianlun,R.raw.jimoyanhuo); player.start(); addTimer(); } catch (Exception e){ e.printStackTrace(); } } public void pause(){ Log.d(TAG,"pause"); player.pause(); } public void continueplay(){ Log.d(TAG,"continueplay"); player.start(); } public void seekTo(int progress){ Log.d(TAG,"seekTo"+progress); player.seekTo(progress); } } @Override public void onDestroy(){ super.onDestroy(); if (player == null) return;; if(player.isPlaying())player.stop(); player.release(); player=null; } }
时间: 2024-02-15 17:27:12 浏览: 138
zds_setup_5.2.16.3_azrjy.zip_android_zds软件
这是一个用于播放音乐的Service类,其中包含一个MediaPlayer对象和一个Timer对象。它通过绑定到Activity来控制MediaPlayer的播放、暂停、继续播放和跳转进度等操作。同时,它还通过Timer对象和Handler对象来更新播放进度,以便在界面上显示当前播放进度和总时长。在onCreate()方法中初始化MediaPlayer对象,在onBind()方法中返回一个Binder对象用于Activity和Service之间的通信。在MusicControler类中实现了控制音乐播放的方法,其中play()方法用于播放音乐并启动计时器,pause()方法用于暂停播放,continueplay()方法用于继续播放,seekTo()方法用于跳转进度。最后,在onDestroy()方法中释放MediaPlayer对象,停止播放音乐。
阅读全文