java - 在服务类中使用 MediaPlayer...?

标签 java android android-service android-mediaplayer android-intentservice

我正在制作一个应用程序,目前我正在努力为其添加背景音乐。我已经看到了很多方法可以做到这一点,并且我选择使用服务来实现它。 然而,当我调用该服务时,我的问题出现了,由于我什么也没听到,所以音乐不播放!我与另一个示例进行了比较,并尝试了几乎所有内容,但没有任何变化...相反,我正在使用 IntentService 来播放音乐(至少有一些东西),但它不是很好,因为例如,当我按下主页按钮时,音乐继续播放...

服务类的代码如下:

    package edu.ub.pis2016.darmas.entrega1;


    import android.app.Service;
    import android.content.Context;
    import android.content.Intent;
    import android.media.AudioManager;
    import android.media.MediaPlayer;
    import android.os.IBinder;
    import android.widget.Toast;


    public class Service_1 extends Service {

        MediaPlayer player;


        public IBinder onBind(Intent arg0) {

            return null;
        }

        @Override
        public void onCreate(){
            super.onCreate();
            player = MediaPlayer.create(this, R.raw.calm);
            player.setLooping(true); // Set looping
            player.setVolume(100,100);
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId){
            player.start();

            return 1;
        }


        @Override
        public void onDestroy(){
            player.stop();
            player.release();
            player = null;
        }


        public void onStop(){
            player.stop();
        }

        public void onPause(){

        }


    }

我通过执行以下操作从我的一项 Activity 中调用该服务:

Intent intent = new Intent(this, Service_1.class);
startService(intent);

但是没用... 相反,这是我的 IntentService 类的代码:

    package edu.ub.pis2016.darmas.entrega1;

    import android.app.IntentService;
    import android.content.Context;
    import android.content.Intent;
    import android.media.AudioManager;
    import android.media.MediaPlayer;
    import android.os.IBinder;
    import android.view.KeyEvent;
    import android.widget.Toast;

    /*
    *  Service_music Class which extends from IntentService class. We do   this    due to with this latter,
    *  there's no need to implement a thread thanks to it creates by  default (a worker thread),
    *  which runs in the background. Also, this class implements from  Audiomanager, in order to
    *  control the different situations in where the music can be found  through the phone.
    *
    */
    public class Service_music extends IntentService implements AudioManager.OnAudioFocusChangeListener {

        MediaPlayer mp;
        AudioManager audioManager;
        boolean end = false;



        /*
        *  ------------------------------------------------
        *  -            Class Itself Methods              -
        *  ------------------------------------------------
        */

        // Constructor class, required! We create here our worker thread
        public Service_music() {
            super("Service_music_thread");
        }


        public IBinder onBind(Intent arg0) {

            return null;
        }

        @Override
        protected void onHandleIntent(Intent intent) {

            lets_play_music();
            while (end != true){}
        }


        @Override
        public void onDestroy(){
            super.onDestroy(); // It's mandatory to call the super() methods when extending from IntentService
            if (this.mp != null) releaseMediaPlayer();

        }


        /*
        *  ------------------------------------------------
        *  -             Initialize Methods               -
        *  ------------------------------------------------
        */

        // Method to initialize the media player
        private void initializeMediaPlayer(){
            //this.mp = MediaPlayer.create(this, R.raw.calm);
            this.mp = MediaPlayer.create(this, R.raw.barefootandbruisdjamestownstory);
            this.mp.setLooping(true);
            this.mp.start();
        }


        private void initializeAudioManager(){
            this.audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);

            if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                // could not get audio focus.
                Toast.makeText(getApplicationContext(), "Ha habido un error al iniciar la musica :(", Toast.LENGTH_SHORT).show();
            }
        }

        /*
        *  ------------------------------------------------
        *  -               Auxiliar Methods               -
        *  ------------------------------------------------
        */

        // This method will carry the task of playing the music, but notice this is only for local media!
        private void lets_play_music(){
            initializeAudioManager();
            initializeMediaPlayer();
            //initializeAudioManager();
            //this.mp.start();
        }


        // Method to release all resources taken by the mp object
        private void releaseMediaPlayer(){
            this.mp.stop();
            this.mp.release();
            this.mp = null;
        }


        /*
        *  ------------------------------------------------
        *  -            Audio Manager Methods             -
        *  ------------------------------------------------
        */

        public void onAudioFocusChange(int focusChange) {
            // Do something based on focus change...
            switch (focusChange){

                // Case if we have gained the focus to play!
                case AudioManager.AUDIOFOCUS_GAIN:
                    if (this.mp == null) initializeMediaPlayer(); // If we had to release the mp by any reason, we re-initialize it!
                    else if(!this.mp.isPlaying()) {
                       this.mp.setLooping(true);  // In theory, it should play looping through infinitely
                       this.mp.start(); // If it's not currently playing, starts!
                    }
                    this.mp.setVolume(1.0f, 1.0f);  // We set the volume!
                    break;

                // Case if we have completely (or almost) lost the focus
                case AudioManager.AUDIOFOCUS_LOSS:
                    if (this.mp.isPlaying()) this.mp.stop(); // If it's currently playing, we have to stop it first
                    end = true;
                    releaseMediaPlayer();  // We release the resources
                    break;

               // Case if we have lost the focus for a short period of time
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    if (this.mp.isPlaying()) this.mp.pause(); // If it's currently playing, we just pause it!
                    break;

                // Case if we have lost the focus but for a tiny piece of time, so we're allowed to continue performing the music but in a quiet state!
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    if (this.mp.isPlaying()) this.mp.setVolume(0.3f, 0.3f); // If it's currently playing, we just set the volume to a quiet level!
                    break;
            }
        }


    }

后者有效,但“音频管理器”无效,当我按下“主页按钮”时,音乐继续播放......

如果有人可以帮助我,或者告诉我错误在哪里,或者我做错了什么,来解决这个问题,我将非常感激,因为我对此感到生气......

最佳答案

两个猜测(由于缺乏完整代码):

您的 list 不包含该服务,因此它不会收到 Intent R.raw.value不存在

关于java - 在服务类中使用 MediaPlayer...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37499177/

相关文章:

android - 他们同时启动两个连续服务是否有任何负面影响?如果是这样,有哪些替代方案?

android - 防止动态壁纸改变屏幕方向

android - 解绑服务但不销毁它

java - 插入二进制堆时出现 NullPointerException?

用于加密的java包

java - 从 servlet(或 servlet 过滤器)中获取 JSP 名称

java - .jsp动态表创建

Android 应用程序在某些手机上使用的 RAM 多于最大堆大小

android - 如何在代码中禁用物理键盘(一直使用虚拟键盘)

android - 我应该使用后台服务还是 AsyncTask 足以完成这项任务?