Explicit addressing an Intent to a dynamically broadcast receiver

拈花ヽ惹草 提交于 2019-12-18 15:04:35

问题


i am new to Android and trying to understand the communication between apps.

I am trying to write 3 little apps which can communicate with each other. If you want to sent a message to everybody you just use an implicit broadcast.

implicit Intent intent.setAction("com.example.myChatMessage")

if you want to adress only 1 specifc receiver i did it with

explicite Intentintent.setComponent("com.example.test.android.broadcastreceiver.b", "com.example.test.android.broadcastreceiver.b.myBroadcastReceiver")

this works, when the broadcast receiver is a seperate class and defined in the AndroidManifest.xml.

My Question: Is it possible to explicit adress a dynamicall registered broadcast receiver?

package com.example.test.android.broadcastreceiver.b;

public class MainActivity extends Activity {

private final IntentFilter intentfilter = new IntentFilter("com.example.myChatMessage");
private myBroadcastReceiver broadcastreceiver;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    broadcastreceiver = new myBroadcastReceiver();
    registerReceiver(broadcastreceiver, intentfilter);
}

public static class myBroadcastReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        String message = intent.getStringExtra("message");
        Log.d("message", "B received: "+message);       
    }
}
}

It receives all implicit broadcasts but no explicit one - i don't know hot to adress it. Can you help me?


回答1:


It does not appear possible to send an explicit intent to a dynamically registered broadcast receiver. Registering the receiver in AndroidManifest.xml is the only way.

If you dynamically register a BroadcastReceiver – by calling Context.registerReceiver() – you supply a BroadcastReceiver instance ... If you try to send an Intent to the receiver by naming the class of the BroadcastReceiver, it will never get delivered .. The Android system will not match the Intent you declared to the class of the BroadcastReceiver instance you registered.

Source: http://onemikro2nd.blogspot.com/2013/09/darker-corners-of-android.html



来源:https://stackoverflow.com/questions/14810134/explicit-addressing-an-intent-to-a-dynamically-broadcast-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!