【问题标题】:Running a bound service and a thread运行绑定服务和线程
【发布时间】:2016-12-23 09:02:24
【问题描述】:

我的主要活动目前有一个绑定服务。

我想知道是否有可能在这个绑定的服务中运行一个线程,它可以将整数传递给我的主活动。此服务需要使用任何新的随机数整数自动更新我的主活动的文本视图,而无需单击按钮。

我应该研究处理程序吗?还是消息/捆绑包??

任何帮助将不胜感激!谢谢 !

【问题讨论】:

  • 使用Handler你可以做到
  • 处理程序是正确的方法吗?如果是这样,我如何将我当前的处理程序从 Main Activity 传递给 Service?

标签: android multithreading service


【解决方案1】:

您可以在 MainActivity 中定义一个接收器,然后可以使用向该接收器发送广播来更新您的 UI。这是一种简单的方法

在您的服务中只需定义一个意图并将值放入其中,如下所示

Intent i = new Intent();
i.setAction("RECEIVERACTION");
i.putExtra("data", "mydata");
sendBroadcast(i);

在你的活动中

public static class Receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String data = intent.getStringExtra("data");
        textView.setText(data);
    } 
} 

希望对你有帮助!!!

【讨论】:

  • LocalBroadcastManager.getInstance(this).registerReceiver(new MainActivity.Receiver(), new IntentFilter("RECEIVERACTION"));不要忘记在您的服务中添加上述行
【解决方案2】:

请阅读 api 指南。具体

https://developer.android.com/guide/components/bound-services.html https://developer.android.com/guide/components/services.html

这应该给你一个很好的前进思路和代码示例

【讨论】:

  • 您好,我已经阅读了这两个文档,但对于哪种方法最适合此方法仍然有点困惑?我只能看到 Messenger?
  • 是的,您可以按照文档中给出的代码示例并使用 messenger。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多