安卓Service音乐播放器

安卓Service音乐播放器
1.目录
安卓Service音乐播放器_第1张图片
2.对按钮进行初始化和监听

public void onClick(View v) {
        Intent intent =new Intent(this,MusicService.class);
        if(btn_play == v){
            intent.putExtra("action","play");
            startService(intent);
        }else if(btn_preview == v){
            intent.putExtra("action","preview");
            startService(intent);
        }else if(btn_stop == v){
            intent.putExtra("action","stop");
            startService(intent);
        }else if(btn_next == v){
            intent.putExtra("action","next");
            startService(intent);
        }
    }

3.启动服务

 public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getStringExtra("action");
        if("play".equals(action)){
            playmusic();
        }else if("preview".equals(action)){
            premusic();
        }else if("stop".equals(action)){
            stopmusic();
        }else if("next".equals(action)){
            nextmusic();
        }
        return super.onStartCommand(intent, flags, startId);
    }

4、四个功能
播放

private void playmusic() {
        if(mediaPlayer==null){
            mediaPlayer = MediaPlayer.create(this,list[cur]);
        }
        mediaPlayer.start();
    }

停止

private void stopmusic() {
        if(mediaPlayer!=null)
            mediaPlayer.stop();
    }

下一首

private void nextmusic() {
        cur = (cur + 1)%list.length;
        if(mediaPlayer != null){
            mediaPlayer.release();
        }
        mediaPlayer = MediaPlayer.create(this,list[cur]);
        mediaPlayer.start();
    }

上一首
注:当歌曲为第一首歌时,上一首为最后一首歌:
if(cur < 0){ cur = list.length - 1;}

private void premusic() {
        cur = (cur - 1)%list.length;
        if(cur < 0){
            cur = list.length - 1;
        }
        if(mediaPlayer != null){
            mediaPlayer.release();
        }
        mediaPlayer = MediaPlayer.create(this,list[cur]);
        mediaPlayer.start();
    }

5、截图
安卓Service音乐播放器_第2张图片
6、github:https://github.com/summer367/Test/tree/master/musicservice

你可能感兴趣的:(安卓)