我有一个 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 不属于适配器类。
答案 0 :(得分:0)
根本原因::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);
}
});