【问题标题】:Communication between Service and any ActivityService 和任何 Activity 之间的通信
【发布时间】:2016-05-02 05:31:02
【问题描述】:

我有一个从服务发送消息到活动的代码。但我只向创建服务的活动发送消息。 如果我更改活动并且服务仍然处于活动状态,我需要在新活动中接收消息。怎么样?

我使用这个代码:

活动

public static Handler messageHandler = new MessageHandler();

...


    public static class MessageHandler extends Handler {
        @Override
        public void handleMessage(Message message) {
            int state = message.arg1;
            switch (state) {
            case HIDE:
                progressBar.setVisibility(View.GONE);
                break;
            case SHOW:
                progressBar.setVisibility(View.VISIBLE);
                break;
            }
        }
    }

然后,我创建传递处理程序的服务。

Intent startService = new Intent(context, SERVICE.class)
startService.putExtra("MESSENGER", new Messenger(messageHandler));
context.startService(startService);

更改活动时,我停止接收消息。我可以在任何活动中创建一个 messageHandler 类吗?那是工作吗?谢谢!

【问题讨论】:

标签: android android-activity android-service


【解决方案1】:

看看EventBus库:

还可以阅读Observer pattern

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多