为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

HUX布斯 2022-07-14 09:38:23
我有一个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 回答

?
慕容708150

TA贡献1831条经验 获得超4个赞

根本原因: sendBroadcast是Context类的方法,因为你在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);

    }

});


查看完整回答
反对 回复 2022-07-14
  • 1 回答
  • 0 关注
  • 162 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信