应用在使用服务时被杀死时,音乐会暂停 [英] music pause when app killed when using service

查看:57
本文介绍了应用在使用服务时被杀死时,音乐会暂停的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Service 类在后台播放音乐.当我在顶部显示通知栏时,我的应用程序有问题.当我杀死该应用程序时,音乐会停止大约1秒钟,然后再次开始播放.我不知道是什么问题.

I am using a Service class to play music in the background. While I am displaying the notification bar on top, there is issue in my app. When I kill the app, the music stops for about 1 second and then it starts again. I can't figure out what's the issue.

我正在关注教程.

public class MyMusicService extends Service {

    MediaPlayer mediaPlayer;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public MyMusicService() {
        super();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (mediaPlayer!= null)
        {
            mediaPlayer.release();
        }
        mediaPlayer =MediaPlayer.create(this,R.raw.song);
        mediaPlayer.setLooping(true);
        mediaPlayer.start();

         return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

            mediaPlayer.stop();


    }
}

推荐答案

在主要活动上使用onTaskRemoved,并在此事件上释放媒体播放器.

Use onTaskRemoved on your main activity and release your mediaplayer on this event.

这篇关于应用在使用服务时被杀死时,音乐会暂停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆