绑定服务_简易音乐播放器

PlayService(播放器服务器)

public class PlayService extends Service {
    private MediaPlayer player;

    @Override
    public void onCreate() {
        super.onCreate();
        player = MediaPlayer.create(this, R.raw.happiness);
    }

    // 第一步,创建胶水类
    public class MyBinder extends Binder {
        public PlayService getPlayService() {
            return PlayService.this;
        }
    }


    // 第二步,将胶水涂在Service表面,等待粘贴(绑定)
    @Override
    public IBinder onBind(Intent intent) {
        Log.d("1622", "service onBind");
        return new MyBinder();
    }

    // 播放
    public void start() {
        if (!player.isPlaying()) {
            player.start();
        }
    }

    // 暂停
    public void pause() {
        if (player.isPlaying()) {
            player.pause();
        }
    }

    // 停止
    public void stop() {
        player.stop();
    }



    @Override
    public boolean onUnbind(Intent intent) {
        stop();
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        player.release();
    }
}

MianActivity

public class MainActivity extends AppCompatActivity implements ServiceConnection {

    private PlayService service;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // 开始播放
    public void start(View view) {
        if (service == null) {
            // 第三步,将Activity和Service绑定
            Intent intent = new Intent(this, PlayService.class);
            bindService(intent, this, Context.BIND_AUTO_CREATE);
        } else {
            service.start();
        }
    }

    // 暂停播放
    public void pause(View view) {
        if (service != null) {
            service.pause();
        }
    }

    // 停止播放
    public void stop(View view) {
        if (service != null) {
            unbindService(this);
            service = null;
        }
    }

    // 第四步,绑定成功时,通过Service表面返回的胶水获取Service实例
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        PlayService.MyBinder binder = (PlayService.MyBinder) iBinder;
        // 第五步,获取Service实例,即可执行操作
        service = binder.getPlayService();
        service.start();
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {

    }
}

布局




    

建立raw文件夹放MP3文件
注册

 

你可能感兴趣的:(绑定服务_简易音乐播放器)