Android入门到卸载
2022-01-16 13:05
采纳率: 100%
浏览 114

android 关于音乐app锁屏以后不能自动播放下一曲问题

关于音乐app锁屏以后不能自动播放下一曲问题
近期自己在开发一个音乐app遇到了以下的问题:
锁屏状态下,每当播放完两首歌,到第三首歌的时候就好自动暂停,不能自动下一曲播放,我也尝试过使用PowerManager这个类都是无济于事
但如果是亮屏状态下的时候就是可以正常的自动播放下一曲
以下这个是我的播放完成以后进行下一步操作的代码


```java
 /**
    *这个是一个mediaPlayer播放器的播放完成回到
     * 完成回调
     *
     * @param mp
     **/
    @Override
    public void onCompletion(final MediaPlayer mp) {
        mService.get().mWakeLock.acquire(7200000); //防止死后台
        musicPlayerEnginePlayCallback.onState(PLAY_STATE_FINISH);  //通过这里的接口回调方法来进行下一曲播放
        LogUtil.E(TAG, "onCompletion");
}
一开始我的PowerManager类是通过服务的 onCreate初始化的
 powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "PlayerWakelockTag");


播放服务的全代码
```java



public class PlayService extends MediaBrowserServiceCompat {
    private static final String TAG = "PlayService";
    public PowerManager.WakeLock mWakeLock;
    private IBinder mPlayerPresenter;
    private NotificationBroadcastReceiver notificationBroadcastReceiver;
    public MediaSessionCompat mediaSession;
    public List<Music> playList = new ArrayList<Music>();
    private PowerManager powerManager;

    public PlayerPresenter getPlayerPresenter() {
        return playerPresenter;
    }

    private PlayerPresenter playerPresenter;
    public static List<BroadcastReceiver> receiverList = new ArrayList<BroadcastReceiver>();
    //主线程Handler
    private Handler mMainHandler;
    public static PlayService playService;

    //private IntentFilter intentFilter = new IntentFilter(ACTION_SERVICE);
    public static final String ACTION_SERVICE = "com.yfoo.listen.playService.PlayService";// 广播标志
    private static final String CHANNEL_ID = "com.yfoo.listen.playService.channel";
    private static final String ACTION_PAUSE_PLAY = "com.yfoo.listen.playService.MusicNotification.pausePlay";
    private static final String ACTION_PREVIOUS = "com.yfoo.listen.playService.MusicNotification.previous";
    private static final String ACTION_NEXT = "com.yfoo.listen.playService.MusicNotification.next";
    private static final String ACTION_LIKE = "com.yfoo.listen.playService.MusicNotification.like";

    private static final String MY_MEDIA_ROOT_ID = "media_root_id";
    private static final String MY_EMPTY_MEDIA_ROOT_ID = "empty_root_id";
    private static NotificationOld notificationOld;

    public static final String CMD_TOGGLE_PAUSE = "toggle_pause";//按键播放暂停
    public static final String CMD_NEXT = "next";//按键下一首
    public static final String CMD_PREVIOUS = "previous";//按键上一首
    public static final String CMD_PAUSE = "pause";//按键暂停
    public static final String CMD_PLAY = "play";//按键播放
    public static final String CMD_STOP = "stop";//按键停止
    /**
     * 按键停止
     */
    public static final String CMD_FORWARD = "forward";//按键停止
    /**
     * 按键停止
     */
    public static final String CMD_REWIND = "reward";//按键停止
    /**
     * 状态改变
     */
    public static final String SERVICE_CMD = "cmd_service";//状态改变
    /**
     * 状态改变
     */
    public static final String FROM_MEDIA_BUTTON = "media";//状态改变
    /**
     * 状态改变
     */
    public static final String CMD_NAME = "name";//状态改变
    /**
     * 音量改变增加
     */
    public static final String UNLOCK_DESKTOP_LYRIC = "unlock_lyric"; //音量改变增加

    /**
     * 启动Service服务,执行onStartCommand
     *
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            final String action = intent.getAction();
            final String command = SERVICE_CMD.equals(action) ? intent.getStringExtra(CMD_NAME) : null;
            LogUtil.D(TAG, "onStartCommand");

            if (CMD_NEXT.equals(command) || ACTION_NEXT.equals(action)) {
                playerPresenter.onNext();
            } else if (CMD_PREVIOUS.equals(command)) {
                playerPresenter.onPrev();
            } else if (CMD_PAUSE.equals(command)) {
                PlayerPresenter.engine.pause();
                playerPresenter.stopTimer();
                playerPresenter.createNotification("Pause", playerPresenter.music);
            } else if (CMD_PLAY.equals(command)) {
                PlayerPresenter.engine.start();
                playerPresenter.starTimer(0, 100);
                playerPresenter.createNotification("play", playerPresenter.music);
            }

        }
        return START_NOT_STICKY;
    }

    public static void stopService() {
        if (playService != null) playService.onDestroy();
        playService = null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        playService = this;
        LogUtil.D(TAG, "onCreate");
        if (mPlayerPresenter == null) {
            mediaSession = new MediaSessionCompat(this,
                    "PlayService",
                    new ComponentName(App.getContext().getPackageName(),
                            HeadsetButtonReceiver.class.getName()), null);
            super.setSessionToken(mediaSession.getSessionToken());

            mPlayerPresenter = new PlayerPresenter(this);
            playerPresenter = (PlayerPresenter) mPlayerPresenter;

            initHeadsetButton();
        }
        notificationOld = new NotificationOld(this);

        DownloadBroadcastReceiver downloadBroadcastReceiver = new DownloadBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(Config.DownloadBroadcastReceiverAction);
        this.registerReceiver(downloadBroadcastReceiver, intentFilter);
        receiverList.add(downloadBroadcastReceiver);

        SqlUtil.openDatabase(this, Config.DataBasePath);

        initConfig();
        BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String singer = intent.getStringExtra("singer");
                String song = intent.getStringExtra("song");
                String path = intent.getStringExtra("path");
                String image = intent.getStringExtra("image");
                String image2 = intent.getStringExtra("image2");
                String tag = intent.getStringExtra("tag");
                String type = intent.getStringExtra("type");

                Music music = new Music();
                music.setSinger(singer);
                music.setName(song);
                music.setPath(path);
                music.setCoverPath(image);
                music.setImage2(image2);
                music.setTag(TextUtils.isEmpty(tag) ? "null" : tag);
                music.setType(TextUtils.isEmpty(type) ? "null" : type);
                playerPresenter.onStartMusic(music);

                //PublicMode.playList.add(0,music);
                //new Media(new WeakReference<>(PlayService.this)).播放音乐3(R.raw.birds);
            }
        };
        registerReceiver(broadcastReceiver, new IntentFilter(Config.PlayMusicAction));
        receiverList.add(broadcastReceiver);

        BroadcastReceiver broadcastReceiver2 = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent != null) {
                    String music_name = intent.getStringExtra("name");
                    String sort_title = intent.getStringExtra("title");
                    String path = intent.getStringExtra("path");
                    String image = intent.getStringExtra("image");
                    String image2 = intent.getStringExtra("image2");
                    String tag = intent.getStringExtra("tag");
                    String type = intent.getStringExtra("type");
                    String background_video = intent.getStringExtra("background_video");

                    Music music = new Music();
                    music.setName(music_name);
                    music.setSinger(sort_title);
                    music.setPath(path);
                    music.setCoverPath(image);
                    music.setImage2(image2);
                    music.setTag(tag);
                    music.setType(type);
                    music.setBackgroundVideo(background_video);
                    PlayerPresenter.engine.pause();
                    playerPresenter.stopTimer();
                    NotificationManager notifManager = (NotificationManager) PlayService.this.getSystemService(Context.NOTIFICATION_SERVICE);
                    notifManager.cancelAll();
                    playerPresenter.mWhiteNoiseAudio.stopAll();
                    playerPresenter.mWhiteNoiseAudio.startPlay(music);
                    PublicMode.music = music;
                }

            }
        };
        registerReceiver(broadcastReceiver2, new IntentFilter(Config.PlayAudioAction));
        receiverList.add(broadcastReceiver2);


//        IntentFilter intentFilter3= new IntentFilter("android.intent.action.MEDIA_BUTTON");
//        intentFilter3.addAction("android.media.AUDIO_BECOMING_NOISY");
//        intentFilter3.addAction("android.media.browse.MediaBrowserService");
//
//        HeadsetButtonReceiver headsetButtonReceiver = new HeadsetButtonReceiver();
//        registerReceiver(headsetButtonReceiver, intentFilter3);
//        receiverList.add(headsetButtonReceiver);
    }


    /**
     * 初始化耳机监听
     */
    private void initHeadsetButton() {
        try {
            HeadsetListenUtil headsetListenUtil = new HeadsetListenUtil(this);
            headsetListenUtil.startListenButton(new HeadsetListenUtil.MediaButtonCallBack() {
                @Override
                public void onMediaButton(int code) {
                    Log.d(TAG, "action onMediaButton  keyCode : " + code);
                    if (code == 4) {
                        playerPresenter.onNext();
                        return;
                    } else if (code == 3) {
                        playerPresenter.onPrev();
                        return;
                    }
                    playerPresenter.onPlayOrPause();
                }

                @Override
                public void onMediaOnClick(int i) {
                    Log.d(TAG, "action onMediaOnClick  keyCode : " + i);
                }
            }, mediaSession);


            headsetListenUtil.startListenState(new HeadsetListenUtil.HeadsetConnectEvent() {
                /**
                 * 耳机连接事件
                 */
                @Override
                public void onConnectEvent() {
                    if (!PlayerPresenter.engine.isPlaying()) {
                        playerPresenter.onPlayOrPause();
                    }
                    Log.d(TAG, "action 耳机连接事件");
                }

                @Override
                public void onOffEvent() {
                    Log.d(TAG, "action 耳机断开事件");
                    if (PlayerPresenter.engine.isPlaying()) {
                        playerPresenter.onPlayOrPause();
                    }
                }
            });
        } catch (Exception e) {
            Log.e(TAG, e + "");
        }

    }


    /**
     * Called by the system to notify a Service that it is no longer used and is being removed.  The
     * service should clean up any resources it holds (threads, registered
     * receivers, etc) at this point.  Upon return, there will be no more calls
     * in to this Service object and it is effectively dead.  Do not call this method directly.
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            for (BroadcastReceiver broadcastReceiver : receiverList) {
                unregisterReceiver(broadcastReceiver);
            }
            NotificationManager notifManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            notifManager.cancelAll();
            notificationOld.unregisterReceiver();

            if (mWakeLock.isHeld())
                mWakeLock.release();//释放屏幕锁
        } catch (Exception e) {
            Log.e(TAG, "用户自行结束程序时候崩溃的: " + e);
        }

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        Log.d(TAG, "IBinder...");
        return mPlayerPresenter;
    }


    /**
     * 参数配置,AudioManager、锁屏
     */
    @SuppressLint("InvalidWakeLockTag")
    private void initConfig() {
        //初始化主线程Handler
        //mMainHandler = new Handler(Looper.getMainLooper());
        powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "PlayerWakelockTag");
    }

    @Nullable
    @Override
    public BrowserRoot onGetRoot(@NonNull String clientPackageName, int clientUid,
                                 @Nullable Bundle rootHints) {
        return new BrowserRoot(MY_EMPTY_MEDIA_ROOT_ID, null);
    }


    @Override
    public void onLoadChildren(@NonNull String
                                       parentId, @NonNull Result<List<MediaBrowserCompat.MediaItem>> result) {

    }

    public String getAudioId() {
        return "";
    }

    public String getTitle() {
        return "";
    }


    /**
     * 播放器逻辑处理类
     */
    public static class PlayerPresenter extends Binder implements UiCallback {
        private static final String TAG = "PlayerPresenter";

        /***总倒计时毫秒*/
        public long TotalMilliseconds; //总倒计时毫秒

        private final WeakReference<PlayService> mService;

        private static String PlayTime;
        public boolean isBuffer = false;

        public WhiteNoiseAudio getmWhiteNoiseAudio() {
            return mWhiteNoiseAudio;
        }

        private final WhiteNoiseAudio mWhiteNoiseAudio; //白噪音播放类
        private CountDownTimerSupport mTimer;
        private static final String id = "channel_1";
        /**
         * 通知管理类
         */
        private NotificationManager manager;

        public Music getMusic() {
            return music;
        }

        private Music music;

        public MusicPlayerEngine getEngine() {
            return engine;
        }

        private Context context;
        private static MusicPlayerEngine engine;
        private static PlayCallback playCallback;

        /**
         * 获取播放状态
         */
        public int getmCurrentState() {
            return mCurrentState;
        }

        /**
         * 获取当前时长
         */
        public static String getCurrentTime() {
            return PlayTime == null || PlayTime.equals("null") ? "00:00" : PlayTime;
        }


        /***
         * 获取总时长
         * @return
         */
        public static String getPlayTime() {
            return MusicPlayerEngine.secToTime((int) engine.getDuration() / 1000);
        }

        /***
         *获取进度中长度
         * @return
         */
        public int getSeekbarMax() {
            return (int) engine.getDuration();
        }


        public void onDestroy() {
            if (manager != null) manager.cancelAll();
            if (mService != null) {
                mService.get().onDestroy();
            }
        }


        private int mCurrentState = PLAY_STATE_STOP;
        private Timer timer;
        private SeekTimeTask timeTask;
        private int time; //当前歌曲时长
        private final MyHandler myHandler;


        public PlayerPresenter(final PlayService service) {
            this.mService = new WeakReference<>(service);
            engine = new MusicPlayerEngine(service);

            context = service;
            myHandler = new MyHandler();
            service.notificationBroadcastReceiver = new NotificationBroadcastReceiver(this);
            receiverList.add(service.notificationBroadcastReceiver);
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ACTION_PAUSE_PLAY);
            intentFilter.addAction(ACTION_PREVIOUS);
            intentFilter.addAction(ACTION_NEXT);
            intentFilter.addAction(ACTION_LIKE);
            service.registerReceiver(service.notificationBroadcastReceiver, intentFilter);

            this.mWhiteNoiseAudio = new WhiteNoiseAudio(this.mService, service.mediaSession);


            engine.setPlayCallback(new MusicPlayerEngine.MusicPlayerEnginePlayCallback() {
                @Override
                public void onState(int state) {
                    LogUtil.D(TAG, "状态: " + state);
                    mCurrentState = state;
                    Intent intent = new Intent();
                    intent.setAction(Config.PlayCallbackBroadcastReceiverAction);

                    switch (state) {
                        case PLAY_STATE_ERROR:

                            break;
                        case PLAY_STATE_WAIT:

                            break;
                        case PLAY_STATE_READY:

                            break;
                        case PLAY_STATE_START: //2
                            mWhiteNoiseAudio.stopAll(); //停止播放所有白噪音
                            //通知UI界面更新
                            if (playCallback != null)
                                playCallback.onDuration(MusicPlayerEngine.secToTime((int) engine.getDuration() / 1000)); //总时长);
                            //startPlayerActivity();
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        Thread.sleep(500);
                                        Looper.prepare();
                                        createNotification("play", music);
                                        Looper.loop();
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).start();
                            intent.putExtra("playState", "play");
                            PublicMode.playState = "play";

                            break;
                        case PLAY_STATE_CONTINUE: //3
                            mWhiteNoiseAudio.stopAll(); //停止播放所有白噪音
                            if (playCallback != null) playCallback.onContinue();
                            intent.putExtra("playState", "continue");
                            PublicMode.playState = "continue";
                            break;
                        case PLAY_STATE_PAUSE: //4
                            if (playCallback != null) playCallback.onPause();
                            intent.putExtra("playState", "pause");
                            PublicMode.playState = "pause";
                            break;
                        case PLAY_STATE_FINISH: //5
                            if (playCallback != null) playCallback.onStop();
                            onNext();
                            break;
                        case PLAY_STATE_BUTTER: //6
                            if (playCallback != null)
                                playCallback.onDuration(MusicPlayerEngine.secToTime((int) engine.getDuration() / 1000)); //总时长);
                            // isBuffer = true;
                            break;
                        case PLAY_STATE_BUTTER_FINISH: //7
                            //isBuffer = false;
                            break;
                        case PLAY_STATE_STOP:
                            if (playCallback != null) playCallback.onStop();
                            intent.putExtra("playState", "stop");
                            PublicMode.playState = "stop";
                            break;

                    }
                    if (playCallback != null) playCallback.onPlayState(state);
                    service.sendBroadcast(intent);
                    LogUtil.D(TAG, "播放状态:" + PublicMode.playState);
                }

                @Override
                public void onDuration(int time) {
                    PlayerPresenter.this.time = time;
                    //playCallback.onDuration(time);
                    //playCallback.onDuration(engine.secToTime((int) time / 1000)); //总时长);
                }
            });


            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Music music = loadingPlayHistory();
                        if (music != null) {
                            PublicMode.isHistory = true;
                            Thread.sleep(500);
                            Looper.prepare();
                            PlayerPresenter.this.music = music;
                            loadImage(music);
                            //onStartMusic(music);
                            PublicMode.playList.add(0, music);
                            PublicMode.playIndex = 0;
                            Thread.sleep(500);
                            engine.pause();
                            stopTimer();
                            createNotification("Pause", music);
                            Looper.loop();
                        } else {
                            PublicMode.isHistory = false;
                        }

                    } catch (Exception ignored) {
                        LogUtil.D(TAG, "ignored" + ignored);
                    }
                }
            }).start();

        }


        public void setPlayCallback(PlayCallback playCallback) {
            PlayerPresenter.playCallback = playCallback;
            LogUtil.D(TAG, "setPlayCallback");
        }


        /**
         * 取消接口通知的注册
         */
        @Override
        public void unRegisterViewController() {

        }

        /**
         * 开始播放
         *
         * @param music
         */
        @Override
        public void onStartMusic(Music music) {
           
                    startMusic(music);
                 
            
            PublicMode.isHistory = false;
            mWhiteNoiseAudio.stopAll();
        }

        private void startMusic(Music music) {
            stopTimer();
            engine.playMusic(music.getPath());
            LogUtil.D(TAG, "onStartMusic");
            this.music = music;
            loadImage(music);
            createNotification("play", music);
            if (playCallback != null) {
                playCallback.onStart(music);
                playCallback.setLike(isLike(music));
            }
            starTimer(500, 100);
            PublicMode.music = music;
            addPlayHistory(music, music.getType(), music.getTag());
        }

        private void loadImage(Music music) {
            String fileName = Config.imageCacheDir + music.getSinger() + "-" + music.getName() + ".jpg";
            if (new File(fileName).exists()) { //读取本地缓存,判断是否存在
                try {
                    FileInputStream fin = new FileInputStream(fileName);
                    byte[] buffer = new byte[fin.available()];
                    fin.read(buffer);
                    fin.close();
                    readImage(buffer, music);
                    LogUtil.D(TAG, "本地");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else { //不存在将使用网络
                OkHttpUtil okHttpUtil = new OkHttpUtil();
                okHttpUtil.getFile(music.getCoverPath(), new OkHttpUtil.GetFileCallBack() {
                    @Override
                    public void onGetFile(byte[] data, int code) {
                        if (data == null) {
                            return;
                        }
                        if (data.length != 0) {
                            readImage(data, music);
                            outImageFile(data);
                        }
                    }
                });
            }
        }

        private void readImage(byte[] data, Music music) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            music.setImgBitmap(bitmap);
            music.setImageByte(data);
            if (playCallback != null) playCallback.imageGetFinish(music);
            PublicMode.bitmap = bitmap;
            mService.get().sendBroadcast(new Intent("com.yfoo.listen.playService.UPDATE_UI"));
            createNotification("play", music);

        }


        private void outImageFile(byte[] data) {
            try {
                String fileName = Config.imageCacheDir + music.getSinger() + "-" + music.getName() + ".jpg";
                FileOutputStream fout = new FileOutputStream(fileName);
                fout.write(data);
                fout.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }


        /**
         * 播放/暂停
         */
        @Override
        public void onPlayOrPause() {
            if (engine.isPlaying()) {
                engine.pause();
                stopTimer();
                createNotification("Pause", music);
            } else {
                engine.start();
                starTimer(0, 100);
                createNotification("play", music);

            }

        }

        /**
         * 停止播放
         */
        @Override
        public void onStop() {
            engine.stop();
            stopTimer();
        }

        /**
         * 设置播放进度
         *
         * @param seek
         */
        @Override
        public void onSeekTo(int seek) {
            LogUtil.D(TAG, "onSeekTo: " + seek);
            engine.setSeek(seek);
        }

        /***
         * 下一曲
         */
        @Override
        public void onNext() {
            synchronized (this) {
                if (PublicMode.playList.size() == 0) {
                    return;
                }
                PublicMode.playIndex++;
                if (PublicMode.playIndex == PublicMode.playList.size()) {
                    PublicMode.playIndex = 0;
                }
                onStartMusic(PublicMode.playList.get(PublicMode.playIndex));
            }

        }

        /***
         * 上一曲
         */
        @Override
        public void onPrev() {
            synchronized (this) {
                if (PublicMode.playList.size() == 0) {
                    return;
                }
                PublicMode.playIndex--;
                if (PublicMode.playIndex == -1) {
                    PublicMode.playIndex = PublicMode.playList.size() - 1;
                }
                onStartMusic(PublicMode.playList.get(PublicMode.playIndex));
            }

        }


        /**
         * 收藏被单击
         */
        @Override
        public void onLike() {
            if (isLike(music)) {
                if (playCallback != null)
                    playCallback.setLike(!deleteLike(music));//这里删除成功了返回真 回调到UI就是要回调假是取消收藏
            } else {
                if (playCallback != null)
                    playCallback.setLike(addLike(music, music.getType(), music.getTag()));
            }

        }



    }

    




}


  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

4条回答 默认 最新

  • Ztian77 2022-01-18 17:43
    最佳回答

    楼主描述上,代码应该是没问题,现象出现的原因很大可能是运行系统的电源管理上做的暂停动作。楼主试试在播放时,请求持有PowerManager.WakeLock 锁

    评论
    解决 无用
    打赏 举报
查看更多回答(3条)

相关推荐 更多相似问题