How to send and receive broadcast message

前端 未结 3 1817
清歌不尽
清歌不尽 2020-12-02 18:08

I am trying to pass data between two activities that are inside of tabs. I am trying to use sendBroadcast(). With breakpoints set I never reach onReceiv

相关标签:
3条回答
  • 2020-12-02 18:38

    I was having the same problem as you, but I figured out:

    Remove the intent filter from the manifest and change

    Intent intent=new Intent(getApplicationContext(),WebResults.class);
    

    for

    Intent intent=new Intent();
    

    Hope it helps!

    0 讨论(0)
  • 2020-12-02 18:47

    Please use

    intent.getStringExtra("");
    

    and

    new Intent();
    

    Worked for me.

    0 讨论(0)
  • 2020-12-02 18:49

    You can do like this

    Intent intent = new Intent("msg");    //action: "msg"
    intent.setPackage(getPackageName());
    intent.putExtra("message", message.getBody());
    getApplicationContext().sendBroadcast(intent);
    

    Then for receiving write something like this (inside Activity)

    @Override
    protected void onResume() {
        super.onResume();
        mBroadcastReceiver = new BroadcastReceiver(){
    
            @Override
            public void onReceive(Context context, Intent intent){
               /* Toast.makeText(context, "Message is: "+ intent.getStringExtra("message"), Toast.LENGTH_LONG)
                        .show();*/
                String action = intent.getAction();
                switch (action){
                    case "msg":
                        String mess = intent.getStringExtra("message");
                        txt.setText(mess);
                        break;
                }
            }
    
        };
    
        IntentFilter filter = new IntentFilter("msg");
        registerReceiver(mBroadcastReceiver,filter);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mBroadcastReceiver);
    }
    
    0 讨论(0)
提交回复
热议问题