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) {
}
}
布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context="org.mobiletrain.android24_bindserviceplaymusicdemo.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始播放"
android:onClick="start"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="暂停播放"
android:onClick="pause"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止播放"
android:onClick="stop"/>
</LinearLayout>
建立raw文件夹放MP3文件
注册
<service
android:name=".PlayService"
android:enabled="true"
android:exported="true"></service>
网友评论