0

I created object bluetooth-service, where was thread created, which monitors data in queue. 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?

Sauber
  • 33
  • 1
  • 4
  • Show us your correspondening code and show us where you are struggeling. We will try to help you but we won't code a full website for you. – bish Jul 08 '15 at 08:50

2 Answers2

0

Did you think about using a static class that would save the message you need to send, then maybe use the Observer pattern (if needed) for notifying the thread it has a new message to send

Bxtr
  • 316
  • 1
  • 13
  • I can pass object this static class from main activity to second activity through intent? – Sauber Jul 08 '15 at 08:58
  • no, since the class is static (think about using Singleton) you only need to get the instance everytime (static meaning : http://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-a-class) and then ask for the value like `Singleton.getInstance().getValue()` – Bxtr Jul 08 '15 at 09:01
  • if the response suit to your problem /or not let me know – Bxtr Jul 08 '15 at 12:45
0

I use https://github.com/greenrobot/EventBus for that. This will simplify the code. All you need to do is here. In your case you need to:

  1. Add graddle dependency

    compile 'de.greenrobot:eventbus:2.4.0'

  2. 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;
          ...
       }
    }
    
  3. 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);
    } 
    
  4. And finally post your data:

    EventBus.getDefault().post(new MessageEvent("Hello everyone!"));
    

Let me know if this helped.

Karol Żygłowicz
  • 2,442
  • 2
  • 26
  • 35