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

问题描述 投票:0回答:1

我有一个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无法解析,那么如何从我的适配器类发送广播意图?

我也想知道这是否是一种正确的方法,或者是否有更好的方法在适配器中发送广播,因为我读到某处广播接收器不属于适配器类。

java android android-recyclerview broadcastreceiver recycler-adapter
1个回答
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);
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.