我有一个绑定服务,我想通过点击通知停止。
在我的main_activity中,我在onDestroy上执行此操作以取消绑定我的服务:
public void onDestroy(){
super.onDestroy();
if(mediaPlayerBound){
System.out.println(mediaPlayerBound);
unbindService(mServCon);
mMediaPlayerServiceBound = false;
}
这部分工作正常,因为我认为mediaPlayerBound是真的,所以服务没有被绑定。
然后在我的服务中: 收到广播后我会拨打以下电话。
stopForeground(true);
stopSelf();
最后:
在我使用的服务中的OnDestroy中:
public void onDestroy(){
this.unregisterReceiver(nextBroadCast);
System.out.println("Stopped Service");
}
现在我的问题是,我开始用mediaPlayer播放一首歌,但即使在我确认该服务已达到onDestroy后它仍然存在。一旦我调用stopSelf(),我该怎么办才能阻止它播放?
答案 0 :(得分:0)
在服务中,我在某处读到了你不会总是看到onDestroyed已被调用。有很多条款和条件。但正如您所说,您正在接收此事件,请尝试以下代码。但我猜你能够在其中获得你的媒体播放器实例。所以这是一个解决方法
@Override
public void onDestroy() {
super.onDestroy();
this.unregisterReceiver(nextBroadCast);
yourMediaPlayer= MediaPlayer.create(x.this,R.raw.sound);
if(yourMediaPlayer.isPlaying())
{
yourMediaPlayer.stop();
yourMediaPlayer.release();
}
}
答案 1 :(得分:0)
简短说明如果您使用MediaPlayer播放音乐,则会停止MediaPlayer。
将此来源放入Destroy()。
private void stopPlay() {
this.unregisterReceiver(nextBroadCast);
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
mediaPlayer = null;
}
}
答案 2 :(得分:0)
在服务文件中添加此代码。当您的应用关闭时,系统会调用onTaskRemoved
。因此,它会停止服务
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
if(player.isPlaying())
{
player.stop();
}
player.release();
stopSelf();
}
@Override
public void onDestroy() {
if(player.isPlaying())
{
player.stop();
}
player.release();
stopSelf();
}
当您希望停止运行服务时,在您的活动中放置代码。
Intent i=new Intent(this, MediaSongServiece.class);
stopService(i);