按下返回按钮时播放歌曲

3

我尝试在服务中播放歌曲,但当我按下“返回”按钮时,它就停止播放。因此,我重写了onbackpress方法,但这样做直接将我带到了主屏幕。我在不同的片段中显示多个歌曲类别,并通过接口传递ArrayList和位置。这部分没有问题,但我该如何在按下返回按钮时播放歌曲呢?我也尝试重写onpause方法,但出现了一些错误。有什么正确的方法可以实现这一点吗?这是我的播放方法。

  @Override
public void onFragmentInteraction(ArrayList<Songfileinfo> songarr, int position) {
    playAudio(songarr, position);
    Log.v(""+songarr.size(),"I GOT THE SIZE");
}


private void playAudio(ArrayList<Songfileinfo> arrayList, int audioIndex) {
    //Check is service is active
    if (!serviceBound) {
        //Store Serializable audioList to SharedPreferences
        StorageUtil storage = new StorageUtil(getApplicationContext());
        storage.storeAudio(arrayList);
        storage.storeAudioIndex(audioIndex);

        Intent playerIntent = new Intent(this, MediaPlayerService.class);
        startService(playerIntent);
        bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    } else {
        //Store the new audioIndex to SharedPreferences
        StorageUtil storage = new StorageUtil(getApplicationContext());
        storage.storeAudio(arrayList);
        storage.storeAudioIndex(audioIndex);

        //Service is active
        //Send a broadcast to the service -> PLAY_NEW_AUDIO
        Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
        sendBroadcast(broadcastIntent);
    }
}

我重写了返回键的方法后,它播放了音乐。但是在任何片段中都会将我带回主屏幕。

2个回答

1

当播放时,您需要将服务设置为前台。这样,在关闭活动时,服务不会被销毁。当没有播放任何歌曲时,从前台中删除服务。您不需要覆盖返回按钮。


哥们,它只是把通知保留在后台,但当按下返回按钮时不会播放歌曲。 - SAVVY

0

但是当我重写后退按钮时,它会播放歌曲,我应该怎么做才能在按下返回按钮时播放歌曲? - SAVVY
其他媒体播放器会绑定活动,但当您按下包装按钮时,歌曲不会停止。 - SAVVY

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接