如何在recyclerview适配器类中发送广播?

时间:2019-02-27 16:23:50

标签: java android android-recyclerview broadcastreceiver recycler-adapter

我有一个 RecyclerView ,其中显示了在设备上找到的所有歌曲。

适配器类

holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Store songList and songIndex in mSharedPreferences
            storageUtil.storeSong(Main.musicList);
            storageUtil.storeSongIndex(holder.getAdapterPosition());

            //Send media with BroadcastReceiver
            Intent broadCastReceiverIntent = new Intent(Constants.ACTIONS.BROADCAST_PlAY_NEW_SONG);
            sendBroadcast(broadCastReceiverIntent);

            Intent broadCastReceiverIntentUpdateSong = new Intent(Constants.ACTIONS.BROADCAST_UPDATE_SONG);
            sendBroadcast(broadCastReceiverIntentUpdateSong);
        }
    });

我想要实现的是,当在 RecyclerView 中单击歌曲时,会将广播发送到我的服务类中,因此一首歌曲开始播放。

sendBroadcast无法解决,那么如何从适配器类发送广播意图?

我还想知道这是正确的方法还是在适配器中发送广播的更好方法,因为我在某处阅读了 BroadcastReceivers 不属于适配器类。

1 个答案:

答案 0 :(得分:0)

根本原因:sendBroadcastContext类的一种方法,因为您在Adapter类中调用它,所以编译器为何显示错误“ sendBroadcast”无法解决”。

解决方案::从视图实例获取上下文,然后调用sendBroadcast方法。

holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //Store songList and songIndex in mSharedPreferences
        storageUtil.storeSong(Main.musicList);
        storageUtil.storeSongIndex(holder.getAdapterPosition());

        // Obtain context from view instance.
        Context context = v.getContext();

        //Send media with BroadcastReceiver
        Intent broadCastReceiverIntent = new Intent(Constants.ACTIONS.BROADCAST_PlAY_NEW_SONG);
        context.sendBroadcast(broadCastReceiverIntent);

        Intent broadCastReceiverIntentUpdateSong = new Intent(Constants.ACTIONS.BROADCAST_UPDATE_SONG);
        context.sendBroadcast(broadCastReceiverIntentUpdateSong);
    }
});