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

How to send a broadcast in recyclerview adapter class?

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

适配器class

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 中单击一首歌曲时,Broadcast 会发送到我的 服务class所以一首歌开始播放。

sendBroadcast 无法解析,那么如何从我的适配器发送广播意图 class?

我也想知道这是否是正确的方法,或者是否有更好的方法在适配器中发送广播,因为我在某处阅读 BroadcastReceivers don '属于适配器 class。

根本原因:sendBroadcastContextclass的一个方法,因为你在Adapterclass,这就是编译器显示错误 "sendBroadcast cannot be resolved".

的原因

解决方案:从视图实例中获取上下文,然后调用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);
    }
});