0

I have to receive packets in one service and then active activity should receive it. What's the best way to do this? Some handlers, messages, broadcast receivers...?

I have this code in service:

@Override
public void onStart(Intent intent, int startId) {
    Runnable myRunnable = new Runnable() {
  public void run() {
    while(true) {
    try {
        DatagramSocket socket;
        socket = new DatagramSocket(4444);
        socket.setBroadcast(true);
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        socket.receive(packet);
    } catch (IOException e) {
        e.printStackTrace();
    }
     }
   }
};
myThread = new Thread(myRunnable);
myThread.start();
}

How could I send every packet to running activity so this activity will be controlled by packets?

Thanks for answers.

Tunerx
  • 619
  • 9
  • 21

1 Answers1

0

You can use a broadcast receiver indeed. Just let your service send out an intent with a sendBroadcast(...) and your activity should have a broadcast receiver that can receive that and do stuff with it. Multiple activities can receive the same broadcast message. You can use the onPause() and the onResume() functions to change a boolean to see if an activity is running in the foreground, then handle stuff accordingly.

You can look at this thread: How to have Android Service communicate with Activity

MaximumGoat has a nice answer. Search better next time!

Edit: If you create the Intent you want to broadcast, you can put extra information in the Intent with the myIntent.putExtra(String name, variable var). The variable can be lots of types, check this: http://developer.android.com/reference/android/content/Intent.html#putExtra%28java.lang.String,%20double[]%29

You can put multiple extra variables in an intent and retrieve them in the broadcast receiver with the getIntExtra(String name, int default) or getStringExtra(...) or getWhateverExtra(String name, whatever default).

Community
  • 1
  • 1
Josttie
  • 250
  • 2
  • 7
  • I was on that article but somewhere I read that broadcastreceiver should be used only for a few seconds so I wasn't sure that it's good solution. But I will try it, thank You for answer. – Tunerx Jun 27 '13 at 13:20
  • But how could I send packet thru that? When I use `sendBroadcast(new Intent(RefreshTask.REFRESH_DATA_INTENT));` it just send string with identificator but nothing usable... I have never done this – Tunerx Jun 27 '13 at 13:43