[英]how to pass data from not-main activity to thread
I created object bluetooth-service, where was thread created, which monitors data in queue. 我创建了对象bluetooth-service,在其中创建了线程,该对象监视队列中的数据。 From main-activity was one activity created, where i can set data. 从主要活动创建了一项活动,我可以在其中设置数据。 How i can pass data from this activity to thread for sending messages, withount passing object bluetooth-service? 如何在不传递对象蓝牙服务的情况下将数据从此活动传递到线程以发送消息?
您是否考虑过使用静态类来保存您需要发送的消息,然后使用观察者模式 (如果需要)来通知线程它有新消息要发送
I use https://github.com/greenrobot/EventBus for that. 我为此使用https://github.com/greenrobot/EventBus 。 This will simplify the code. 这将简化代码。 All you need to do is here . 您需要做的只是在这里 。 In your case you need to: 在您的情况下,您需要:
Add graddle dependency 添加梯度依赖
compile 'de.greenrobot:eventbus:2.4.0'
create event class: 创建事件类:
public class MessageEvent { public final String message; public YourObject object;//use what you need here to pass data. public MessageEvent(String message) { this.message = message; ... } }
Create Subscribers: 创建订阅者:
@Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } // This method will be called when a MessageEvent is posted public void onEvent(MessageEvent event){ Toast.makeText(context, event.message, Toast.LENGTH_SHORT).show(); } // This method will be called when a SomeOtherEvent is posted public void onEvent(SomeOtherEvent event){ doSomethingWith(event); }
And finally post your data: 最后发布您的数据:
EventBus.getDefault().post(new MessageEvent("Hello everyone!"));
Let me know if this helped. 让我知道是否有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.