How to send data from BroadcastReceiver to Fragmen

2019-07-31 13:57发布

I am trying to make an chatting app.I have a SlidingDrawer Activity and it has many fragments and among which ChatFragment is one.Now when i am sending message to my friend , i have a Chatting Window and if any message comes from GCM service and i am in ChatFragment then this message will go to that Fragment and update the listview as i want to update the chatWindow when any message comes while chatting Now I tried to do like below.

GcmIntentService :

public class GcmIntentService extends IntentService {

    public GcmIntentService() {
        super("GcmIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = gcm.getMessageType(intent);

        if (extras != null && !extras.isEmpty()) {  // has effect of unparcelling Bundle
            // Since we're not using two way messaging, this is all we really to check for
            if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                Logger.getLogger("GCM_RECEIVED").log(Level.INFO, extras.toString());

                showToast(extras.getString("message"));
                Intent sendData = new Intent("chatupdater");
                sendData.putExtra("msg", extras.getString("message"));
                LocalBroadcastManager.getInstance(this).sendBroadcast(sendData);
                Log.i("chat","i am in GCMIntentService");


            }
        }
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

Here i am starting a broadcastreceiver in onHandleIntent().

ChatBroadCastReceiver:

public class ChatBroadCastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("chat","I am in ChatBroadCastReceiver");
        String msg = intent.getStringExtra("msg");
        Log.i("chat",msg);



        //Intent data = new Intent("chatupdater");
        //Intent data = new Intent("chatupdater");
        //data.putExtra("key","data");
        //data.putInt("fragmentno",1); // Pass the unique id of fragment we talked abt earlier
        //context.sendBroadcast(intent);


    }
}

This is my ChatBroadCastReceiver class and if any message comes it successfully receives at the onReceive() method.Now i want to send this message to the Fragment.What i tried , i registered the Fragment with it and tried to get the same data at the onReceive() of ChatFragment.But it didn't call.I tried to see by logging.

public class ChatFragment extends Fragment {

    //ChatBroadCastReceiver mReceiver;
    private EditText et_chat;
    Bundle mailData;
    String caller_mail;
    private ListView chatListview;
    private ChatWindowAdapter chatWindowAdapter;
    private List<ChatSession>PreviousChatSession;
    private List<ChatInfo> chatListItems;
    Button chat_send;
    public ChatFragment() {

    }

    public BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("chat","I am in BroadCastReceiver");
            String msg = intent.getStringExtra("msg");
            Toast.makeText(getActivity(),msg,Toast.LENGTH_LONG).show();
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        mReceiver = new ChatBroadCastReceiver();
        //getActivity().registerReceiver(new ChatBroadCastReceiver(),new IntentFilter("chatupdater"));
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(new ChatBroadCastReceiver(),new IntentFilter("chatupdater"));
        Log.i("chat", "I am in onCreate");

    }

Now how can i get the message which i got in the Broadcastreceiver to the onReceive() of ChatFragment??

2条回答
\"骚年 ilove
2楼-- · 2019-07-31 14:37

Try this

  • Create an interface which will have a method like this.

    public interface DemoListener { public void receiveMessage(String message); }

Now implement this in your fragment and register the listener in BroadcastReceiver, now as soon as your broadcast receiver receives any message it will be available to your fragment via this Listener.
Hope this helps.

查看更多
爷、活的狠高调
3楼-- · 2019-07-31 14:43

To Register your Broadcast You are using:

mReceiver = new ChatBroadCastReceiver();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver ,new IntentFilter("chatupdater"));

So you will Only receive Broadcast on ChatBroadCastReceiver class. Because mReceiver is a Instance of ChatBroadCastReceiver class.

Now to Receive broadcast Message on anonymous class that you have created in your ChatFragment you need to register that like below code. Where mReceiver is a Instance of anonymous BroadcastReceiver class that you have implemented in your ChatFragment class.

LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver ,new IntentFilter("chatupdater"))

To Receive Broadcast Message Both on ChatFragment and ChatBroadCastReceiver you need to register broadcast receiver twice.

LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver ,new IntentFilter("chatupdater"))

ChatBroadCastReceiver mChatBroadCastReceiver = new ChatBroadCastReceiver();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mChatBroadCastReceiver ,new IntentFilter("chatupdater"))

Hope this answer will help you to understand your problem.

查看更多
登录 后发表回答