首先创建一个Music类继承Service
在清单文件中注册
xml************布局
···
<Button
android:id="@+id/tb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="上一首"
android:onClick="pre"
/>
<Button
android:id="@+id/bt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="播放"
android:onClick="play"
/>
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="暂停"
android:onClick="stop"
/>
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下一首"
android:onClick="next"
/>
···
这四个方法在MainActivity中实现
写一下Music中的代码------------------------------------------------
···
//音乐播放器的服务
public class Music extends Service{
@Override
public IBinder onBind(Intent intent) {
//第三步 执行onBind new内部类MyBinder()
return new MyBinder();
}
@Override
public void onCreate() {
//第二步 执行onCreate
super.onCreate();
//MediaPlayer
Log.e("TAG", "准备音乐播放器");
}
@Override
public void onDestroy() {
super.onDestroy();
}
public void next(){
Log.e("TAG", "下一首:甜蜜蜜");
}
public void pre(){
Log.e("TAG", "上一首:画");
}
public void play(){
Log.e("TAG", "播放:一剪梅");
}
public void stop(){
Log.e("TAG", "暂停");
}
public class MyBinder extends Binder implements IService{
public void callNext(){
next();
}
public void callPre(){
pre();
}
public void callStop(){
stop();
}
public void callPlay(){
play();
}
//部分用户调用 播放高品质的音乐
public void playHiFiMusic(){
}
}
}
···
MainActivity中*******************
···
public class MainActivity extends Activity {
private MyConnecton conn;
private MyBinder musicControl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent service = new Intent(this,Music.class);
conn=new MyConnecton();
//第一步:绑定服务
bindService(service, conn, BIND_AUTO_CREATE);
//混合方式开启
startService(service);
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(conn);
}
//上一首
public void pre(View v){
musicControl.callPre();
}//暂停
public void stop(View v){
musicControl.callPre();
}//播放
public void play(View v){
musicControl.callPlay();
}//下一首
public void next(View v){
musicControl.callStop();
}
private class MyConnecton implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//第四步 Service执行完onBind 如果不为空 回调onServiceConnected
//参数IBinder 对象就是onBind的返回值
//获得到这个对象 就可以调用他的公共方法
musicControl=(MyBinder) service;
musicControl.clearCallingIdentity();
//普通用户
IService iservice=(IService) service;
iservice.callNext();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
}
···
网友评论