亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 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 關注
  • 201 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號