【问题标题】:How to Collect info from IntentService and Update Android UI如何从 IntentService 收集信息并更新 Android UI
【发布时间】:2011-12-13 20:46:05
【问题描述】:

我正在学习 Android,但我无法使用我的服务。

我的应用程序每隔 X 秒通过 Socket 连接到我的服务器,接收 XML,解析信息并显示在 TextView 中。

我想知道如何实现 IntenService 来执行此操作以及如何将信息传达给 UI。我发现很难看到好的例子。

感谢您能给我的任何帮助。

谢谢!

【问题讨论】:

    标签: android intentservice


    【解决方案1】:

    使用处理程序并从意图服务向父活动发送消息

    家长活动

    声明处理程序

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
                Bundle reply = msg.getData();
                                // do whatever with the bundle here
                }
    };
    

    调用intentservice:

            Intent intent = new Intent(this, IntentService1.class);
            intent.putExtra("messenger", new Messenger(handler));
            startService(intent);
    

    IntentService内部:

        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            Messenger messenger = (Messenger) bundle.get("messenger");
            Message msg = Message.obtain();
            msg.setData(bundle); //put the data here
            try {
                messenger.send(msg);
            } catch (RemoteException e) {
                Log.i("error", "error");
            }
        }
    

    【讨论】:

    • 我需要使用 AlarmManager 每 x 秒启动一次服务吗?
    • 非常感谢法尔汉!我去看看。
    • 恭喜。您在此示例中使用了最差的变量名称:“msg.setData(data);”数据???真的吗?一切都是数据......
    • 如果 Intent 服务不是从 Activity 而是从 Application 启动的(每 X 秒刷新一次数据)怎么办?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    相关资源
    最近更新 更多