java 活动广播服务(发送消息)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 活动广播服务(发送消息)相关的知识,希望对你有一定的参考价值。

//Create a listener on onCreate:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.setContentView(R.layout.copa);
    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String s = intent.getStringExtra(COPAService.COPA_MESSAGE);
            // do something here.
        }
    };
}

//And register it in onStart:

@Override
protected void onStart() {
    super.onStart();
    LocalBroadcastManager.getInstance(this).registerReceiver((receiver), 
        new IntentFilter(COPAService.COPA_RESULT)
    );
}

@Override
protected void onStop() {
    LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    super.onStop();
}
//Use a LocalBroadCastManager.
LocalBroadcastManager broadcaster;
//In your service's onCreate, set up the broadcaster:
broadcaster = LocalBroadcastManager.getInstance(this);

//IDs
static final public String COPA_RESULT = "com.controlj.copame.backend.COPAService.REQUEST_PROCESSED";
static final public String COPA_MESSAGE = "com.controlj.copame.backend.COPAService.COPA_MSG";

//Send message
public void sendResult(String message) {
    Intent intent = new Intent(COPA_RESULT);
    if(message != null)
        intent.putExtra(COPA_MESSAGE, message);
    broadcaster.sendBroadcast(intent);
}

以上是关于java 活动广播服务(发送消息)的主要内容,如果未能解决你的问题,请参考以下文章

当应用程序不活动时如何发送和确认服务器消息

从另一个活动发送实时消息

通过socket java向多个客户端广播对象

发送广播消息时的奇怪行为

python Socket.IO 客户端,用于向 TornadIO2 服务器发送广播消息

Laravel事件不是广播