service音乐播放

package com.hanqi.text_service;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

public class servicemusic extends AppCompatActivity {
    ProgressBar pb;
    TextView tv1;
    MediaPlayer mediaPlayer;
    Intent intent;
    playSC playSC;
    Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.service);
        tv1=(TextView)findViewById(R.id.tv);
        pb=(ProgressBar)findViewById(R.id.pb);
        intent=new Intent(this,musicservice.class);
        playSC=new playSC();
        //绑定
        bindService(intent,playSC, Context.BIND_AUTO_CREATE);
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what==0){
                    tv1.setText(msg.obj.toString());
                }
            }
        };
    }
    public void b1(View view){
        //向service发送播放指令
        intent.putExtra("action","play");
        startService(intent);
       // tv1.setText("播放状态:开始播放");
    }
    public void b2(View view){
        //向service发送暂停指令
        intent.putExtra("action","pause");
        startService(intent);
       // tv1.setText("播放状态:暂停播放");
    }
    public void b3(View view){
        //向service发送停止指令
        intent.putExtra("action","stop");
        startService(intent);
       // tv1.setText("播放状态:停止播放");
    }
    public void b4(View view){
        //向service发送关闭指令
        b3(view);
        //解除绑定
        if (playSC!=null){
           unbindService(playSC);
            playSC=null;
        }
        stopService(intent);
        finish();
    }
    class playSC implements ServiceConnection{
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            final musicservice.PlayBinder playbind=( musicservice.PlayBinder)service;

            //启动线程
            new  Thread(){
                @Override
                public void run() {
                    while (true){
                        int max=playbind.getMusicDuration();
                        pb.setMax(max);
                        int c=playbind.getMusicCurrentPosition();
                        pb.setProgress(c);
                        Message message=new Message();
                        message.what=0;
                        message.obj=playbind.getPlayState();

                        try {
                            Thread.sleep(500);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }
}

service代码

package com.hanqi.text_service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by Administrator on 2016/6/21.
 */
public class musicservice extends Service {
    MediaPlayer mediaPlayer;
    String strplay="等待播放";
    public musicservice() {
        Log.e("TAG", "MyService被构造");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return new PlayBinder();
    }

    public class PlayBinder extends Binder{
        //得到总长度
        public int getMusicDuration(){
            int rtn=100;
            if (mediaPlayer!=null){
                rtn=mediaPlayer.getDuration();
            }
            return rtn;
        }

        //得到当签名播放进度
        public int getMusicCurrentPosition(){
            int rtn=0;
            if (mediaPlayer!=null){
                rtn=mediaPlayer.getCurrentPosition();
            }
            return rtn;
        }

        //返回当前状态
        public String getPlayState(){

            return strplay;
        }

    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String ac=intent.getStringExtra("action");
        switch (ac) {
            case "play":
                if (mediaPlayer == null) {
                    mediaPlayer = MediaPlayer.create(musicservice.this, R.raw.blue);
                    strplay="开始播放";
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        mediaPlayer.reset();
                        mediaPlayer.release();
                        mediaPlayer = null;
                        strplay="播放完成";
                    }
                });
        }
                mediaPlayer.start();
                break;
            case "pause":
                if (mediaPlayer!=null&&mediaPlayer.isPlaying()){
                    mediaPlayer.pause();
                    strplay="暂停播放";}
                break;
            case "stop":
                if(mediaPlayer!=null){
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                    mediaPlayer.release();
                    mediaPlayer=null;
                    strplay="停止播放";}
                break;
        }

        return super.onStartCommand(intent, flags, startId);
    }
}

形式2

package com.hanqi.text_service;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

public class music2 extends AppCompatActivity {

    ProgressBar pb;
    TextView tv1;
    MediaPlayer mediaPlayer;
    Intent intent;
    //服务连接类的实例
    playserviceconnection pc;
    //代理对象
    music2service.playbind pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.music2);
        tv1=(TextView)findViewById(R.id.tv);
        pb=(ProgressBar)findViewById(R.id.pb);
        intent=new Intent(this,music2service.class);

        //绑定
        pc=new playserviceconnection();
        bindService(intent,pc, Context.BIND_AUTO_CREATE);
    }


    //服务连接类
    class playserviceconnection implements ServiceConnection{
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //得到代理对象
            pd=(music2service.playbind)service;
            Log.e("TAG","获取代理对象");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    public void b1(View view){
        //向service发送播放指令
        pd.play();
        tv1.setText("播放状态:开始播放");
    }
    public void b2(View view){
       pd.pause();
        tv1.setText("播放状态:暂停播放");
    }
    public void b3(View view){
        pd.stop();
        tv1.setText("播放状态:停止播放");
    }
    public void b4(View view){
       pd.stop();
        //解除绑定
        unbindService(pc);
        finish();

    }
}

service

package com.hanqi.text_service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;

/**
 * Created by Administrator on 2016/6/21.
 */
public class music2service extends Service {
    MediaPlayer mediaPlayer;
    public class playbind extends Binder{
        public void play(){

            if (mediaPlayer==null){
                mediaPlayer= MediaPlayer.create(music2service.this, R.raw.blue);
            }
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {

                }
            });
            mediaPlayer.start();
        }

        public void pause(){
            if (mediaPlayer!=null&&mediaPlayer.isPlaying()){
                mediaPlayer.pause();}
        }

        public void stop(){
            if(mediaPlayer!=null){
                mediaPlayer.stop();
                mediaPlayer.reset();
                mediaPlayer.release();
                mediaPlayer=null;}
        }
    }
    playbind pb;
    public  playbind onBind(Intent intent) {
        return pb==null? new  playbind(): pb;
    }



}
原文地址:https://www.cnblogs.com/storm47/p/5619091.html