Using a broadcast intent/broadcast receiver to send messages from a service to an activity

前端 未结 4 1128
轻奢々
轻奢々 2020-12-02 06:32

So I understand (I think) about broadcast intents and receiving messages to them.

So now, my problem/what I can\'t work out is how to send a message from the o

4条回答
  •  Happy的楠姐
    2020-12-02 07:16

    Possibly not relevant at the time of the question being asked but there is now the LocalBroadcastManager in the Android Support Package.

    Works pretty much the same way as normal broadcasts but all "chatter" is local to the app it is running in.

    Advantages:

    • You know that the data you are broadcasting won't leave your app, so don't need to worry about leaking private data.
    • It is not possible for other applications to send these broadcasts to your app, so you don't need to worry about having security holes they can exploit.
    • It is more efficient than sending a global broadcast through the system.

    Example:

    Intent i = new Intent("my.local.intent");
    LocalBroadcastManager.getInstance(context).sendBroadcast(i);
    

    and to receive

    receiver = new MyBroadcastReceiverToHandleLocalBroadcast();
    
    IntentFilter i = new IntentFilter();
    i.addAction("my.local.intent");
    LocalBroadcastManager.getInstance(context).registerReceiver(receiver, i);
    

提交回复
热议问题