【问题标题】:How to send and receive broadcast message如何发送和接收广播消息
【发布时间】:2011-04-23 21:22:24
【问题描述】:

我正在尝试在选项卡内的两个活动之间传递数据。我正在尝试使用sendBroadcast()。设置断点后,我永远无法到达onReceive()。

清单:

<activity
    android:name=".WebResults"
    android:label="@string/app_name">

    <intent-filter>
        <action android:name="com.toxy.LOAD_URL" />
    </intent-filter>         
</activity>

活动发送者:

Intent intent=new Intent(getApplicationContext(),WebResults.class);
intent.setAction("com.toxy.LOAD_URL");
intent.putExtra("url",uri.toString());
sendBroadcast(intent);

活动接收器:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    
    IntentFilter filter = new IntentFilter("com.toxy.LOAD_URL");
    this.registerReceiver(new Receiver(), filter);
}

private class Receiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        String url = arg1.getExtras().getString("url");
        WebView webview =(WebView)findViewById(R.id.webView);
        webview.loadUrl(url);
    }
}

【问题讨论】:

  • 将所有内容放在一个活动中,而不是为选项卡使用单独的活动,您将不再需要尝试使用广播在它们之间进行通信。
  • 如何取消注册这个接收器?

标签: android broadcast message-passing


【解决方案1】:

我和你有同样的问题,但我想通了:

从清单中删除意图过滤器并更改

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

为

Intent intent=new Intent();

希望对你有帮助!

【讨论】:

    【解决方案2】:

    请使用

    intent.getStringExtra("");
    

    和

    new Intent();
    

    为我工作。

    【讨论】:

      【解决方案3】:

      你可以这样做

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

      然后为了接收写这样的东西(在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);
      }
      

      【讨论】:

        猜你喜欢
        • 2018-02-27
        • 2012-06-05
        • 1970-01-01
        • 2012-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-21
        相关资源
        最近更新 更多