如何从 IntentService 收集信息并更新 Android UI

Posted

技术标签:

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

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

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

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

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

谢谢!

【问题讨论】:

【参考方案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 秒刷新一次数据)怎么办?

以上是关于如何从 IntentService 收集信息并更新 Android UI的主要内容,如果未能解决你的问题,请参考以下文章

IntentService:如何正确入队?

向 requestLocationUpdates intentService 发送额外信息会中断位置更新

位置侦听器从服务而不是 IntentService 工作

Android面试收集录9 IntentService详解

如何使用 Intentservice 获取位置信息?

如何在固定时间间隔后使用 IntentService 实现进行轮询?