xml
java
package com.commerce.mybindservicemusic;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private MyServiceConnection myConn;
private MyService.MyBind myBinder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void bangdingfuwu(View view) {
if (myConn==null)
{
myConn =new MyServiceConnection();
}
Intent service = new Intent(MainActivity.this,MyService.class);
bindService(service,myConn,BIND_AUTO_CREATE);
}
public void tingzhi(View view) {
myBinder.tingzhi();
}
public void bofan(View view) {
}
private class MyServiceConnection implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
myBinder=(MyService.MyBind) iBinder;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
}
}
service
package com.commerce.mybindservicemusic;
import android.app.Service;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaParser;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;
import java.io.IOException;
public class MyService extends Service {
private MediaPlayer mp;
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
//
TODO: Return the communication channel to the service.
Toast.makeText(MyService.this, "绑定服务成功", Toast.LENGTH_LONG).show();
if (mp !=null){
if (!mp.isPlaying()) {
} else {
mp.stop();
}
mp.release();
}
mp=new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mp.start();
}
});
AssetFileDescriptor file =getResources().openRawResourceFd(R.raw.music);
try{
mp.setDataSource(file.getFileDescriptor(),file.getStartOffset(),file.getLength());
file.close();
mp.prepareAsync();
}catch (IOException e){
e.printStackTrace();
}
return new MyBind();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
public class MyBind extends Binder{
public void tingzhi(){
mp.pause();
}
public void bofan(){
}
}
}



