我正在尝试使用Android中的服务播放音乐。我正在努力的是停止服务和音乐。这是我的服务:
MediaPlayer mediaPlayer;
public SoundService() {
super("SoundService");
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
protected void onHandleIntent(Intent intent) {
}
@Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.zenenegy);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
return START_STICKY;
}
public void stopp(){
Log.d("SERVICE","STOP");
stopSelf();
}
@Override
public void onDestroy() {
super.onDestroy();
}
当我调用'stopp'方法时,我得到了Log,因此服务应该停止,但音乐继续进行。我不知道如何停止音乐,因为当我尝试使用mediPlayer.stop();方法我总是收到错误消息,所以如果我可以随时停止服务,这将是很好的。以下是活动的代码:
public Button zene;
public boolean hang = true;
SoundService soundService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fomenu);
if(hang){
startService();
}
}
@Override
protected void onResume() {
zene = (Button)findViewById(R.id.zene);
zene.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(hang){
soundService.stopp();
//soundService.onDestroy();
}
hang = !hang;
}
});
super.onResume();
}
public void startService(){
startService(new Intent(getBaseContext(), SoundService.class));
}
public void stopService(){
stopService(new Intent(getBaseContext(),SoundService.class));
}
}
我试过使用stopService();方法,但它没有工作。如果有人知道如何停止服务中的音乐,请回复。
答案 0 :(得分:1)
SoundService.java
x.size
停止的几种方法是使用Bound Services或public void stop(){
Log.d("SERVICE","STOP");
mp.stop();
//release the media player if you want to
stopSelf();
}
识别意图操作,然后致电onStartCommand
它看起来像这样
InYourActivity.java
stop()
SoundService.java
public void stopService(){
Intent stopIntent = new Intent(getBaseContext(),SoundService.class);
intent.setAction(SoundService.ACTION_STOP);
stopService(stopIntent);
}
答案 1 :(得分:0)
您需要为已实例化的MediaPlayer对象的实例调用stop方法。在您的情况下,您的MediaPlayer对象称为mediaPlayer。
以下是一个例子:
public void stopMusic(){
if (mediaPlayer != null && mediaPlayer.isPlaying()){
mediaPlayer.stop();
mediaPlayer.destroy();
}
}