如何发送和接收广播消息

时间:2010-10-11 15:39:17

标签: android broadcast message-passing

我正在尝试在标签内的两个活动之间传递数据。我正在尝试使用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);
    }
}

2 个答案:

答案 0 :(得分:37)

我遇到了和你一样的问题,但我想出了:

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

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

代表

Intent intent=new Intent();

希望它有所帮助!

答案 1 :(得分:0)

您可以这样做

@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);
}

然后用于接收这样的内容(在Activity中)

core-image-selinux