MediaPlayerを頻繁に呼び出して音楽を再生することによるANRの解決策について

18282 ワード

もともとdemoプロジェクトを作ってgitにアップロードしたいのですが、簡単な2つのクラスなので、考えてみればやめましょう.今回は、携帯電話自身の音楽を再生したり、ネット音楽を再生したりする処理方法に分かれています.テストしたいのがコピーして入って1つのRecyclerViewの中でいくつかのネットのデータをテストしてみることができて、やはり顺调なはずです(糸滑机能を持っています)は2种类で、1つのノートにしましょう.....
まずローカル音楽で使われているPlayLocalMusicControllerを献上します
package com.pd.plugin.pd.led.controller;

import android.media.AudioManager;
import android.media.MediaPlayer;

/**
 *         
* bug * ( , )bug, ( ) * Created by Tangxb on 2016/7/5. */
public class PlayLocalMusicController { private MediaPlayer mediaPlayer = new MediaPlayer(); private int position; private PlayMusicCompleteListener listener; public interface PlayMusicCompleteListener { void playMusicComplete(int position); } public void playMusic(final int position, final String url, final int currentPlayTime , final PlayMusicCompleteListener listener) { try { this.position = position; this.listener = listener; mediaPlayer.reset(); mediaPlayer.setDataSource(url); mediaPlayer.setLooping(false); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer player) { mediaPlayer.seekTo(currentPlayTime); } }); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer player) { listener.playMusicComplete(position); stopMediaPlayer(); } }); mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer player, int what, int extra) { stopMediaPlayer(); return false; } }); mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() { public void onSeekComplete(MediaPlayer player) { mediaPlayer.start(); } }); mediaPlayer.prepareAsync(); } catch (Exception e) { e.printStackTrace(); } } public int getCurrentPlayTime() { if (mediaPlayer != null) { return mediaPlayer.getCurrentPosition(); } return 0; } public void stopMediaPlayer() { if (mediaPlayer != null) { mediaPlayer.stop(); } } /** * */ public void onStopForMediaPlayer() { if (mediaPlayer != null) { mediaPlayer.stop(); } if (listener != null) { listener.playMusicComplete(position); } } public void releaseMediaPlayer() { if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer = null; } } }
以下は、ネットワーク再生用のLMediaPlayerManger
package com.pd.plugin.pd.led;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

/**
 *    MediaPlayer  ,              ;         {@link com.pd.plugin.pd.led.controller.PlayLocalMusicController}
 *        http://blog.csdn.net/u011516685/article/details/50510902
 *       stop prepareAsync              ,    stop         MediaPlayer        ,              MediaPlayer  
 *   PlayMusicCompleteListener       ,             GC ,      Handler            
 * Created by Tangxb on 2016/9/1.
 */
public class LMediaPlayerManger {
    private static LMediaPlayerManger instance;
    private MediaPlayer mediaPlayer;
    private HandlerThread playHandlerThread;
    private Handler playHandler;
    /**
     *   
     */
    private static final int PLAY = 101;
    /**
     *   
     */
    private static final int STOP = 102;
    /**
     *   
     */
    private static final int RELEASE = 103;
    /**
     *      
     */
    private static final int ONSTOP = 104;
    private Handler handler;
    private int position;
    private String url;
    private PlayMusicCompleteListener listener;

    /**
     *          
     */
    public interface PlayMusicCompleteListener {
        void playMusicComplete(int position);
    }

    private void createHandlerThreadIfNeed() {
        if (playHandlerThread == null) {
            playHandlerThread = new HandlerThread("playHandlerThread");
            playHandlerThread.start();
        }
    }

    private void createHandlerIfNeed() {
        if (playHandler == null) {
            playHandler = new Handler(playHandlerThread.getLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                        case PLAY:
                            playMusic01();
                            break;
                        case STOP:
                            stopMediaPlayer02();
                            break;
                        case RELEASE:
                            releaseMediaPlayer02();
                            break;
                        case ONSTOP:
                            stopMediaPlayer03();
                            break;
                    }
                }
            };
        }
    }

    private void createPlayerIfNeed() {
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
    }

    private LMediaPlayerManger() {
        handler = new Handler(Looper.getMainLooper());
        createHandlerThreadIfNeed();
        createHandlerIfNeed();
    }

    public static LMediaPlayerManger getInstance() {
        if (instance == null) {
            instance = new LMediaPlayerManger();
        }
        return instance;
    }

    public void playMusic(int position, String url, PlayMusicCompleteListener listener) {
        this.position = position;
        this.url = url;
        this.listener = listener;
        playHandler.sendEmptyMessageDelayed(PLAY, 0L);
    }

    public void playMusic01() {
        createPlayerIfNeed();
        playMusic02(url);
    }

    public void playMusic02(String url) {
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(url);
            mediaPlayer.setLooping(false);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer player) {
                    if (mediaPlayer != null) {
                        mediaPlayer.start();
                    }
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer player) {
                    playMusicComplete();
                    stopMediaPlayer();
                }
            });
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer player, int what, int extra) {
                    stopMediaPlayer();
                    return false;
                }
            });
            mediaPlayer.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stopMediaPlayer() {
        playHandler.sendEmptyMessage(STOP);
    }

    public void onStopForMediaPlayer() {
        playHandler.sendEmptyMessage(ONSTOP);
    }

    /**
     *         setOnPreparedListener setOnCompletionListener null,                    (    ,   )
     */
    public void stopMediaPlayer02() {
        if (mediaPlayer != null) {
            mediaPlayer.setOnPreparedListener(null);
            mediaPlayer.setOnCompletionListener(null);
            try {
                mediaPlayer.stop();
            } catch (IllegalStateException e) {

            }
        }
        mediaPlayer = null;
    }

    /**
     *         setOnPreparedListener setOnCompletionListener null,                    (    ,   )
     */
    public void stopMediaPlayer03() {
        stopMediaPlayer02();
        playMusicComplete();
    }

    /**
     *     ,          UI
     */
    public void playMusicComplete() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (listener != null) {
                    listener.playMusicComplete(position);
                }
            }
        });
    }

    public void releaseMediaPlayer() {
        playHandler.sendEmptyMessage(RELEASE);
    }

    public void releaseMediaPlayer02() {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.stop();
                mediaPlayer.release();
            } catch (IllegalStateException e) {

            }
        }
        mediaPlayer = null;
        //       
        listener = null;
        handler.removeCallbacksAndMessages(null);
    }
}