Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7059127
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T04:11:42+00:00 2026-05-28T04:11:42+00:00

My Android app should do the following: The MainActivity launches another thread at the

  • 0

My Android app should do the following:
The MainActivity launches another thread at the beginning called UdpListener which can receive UDP calls from a remote server. If it receives a packet with a content “UPDATE”, the UdpListener should notify the MainActivity to do something.

(In the real app, the use case looks like this that my app listens on the remote server. If there is any new data available on the remote server, it notifies every client (app) by UDP, so the client knows that it can download the new data by using HTTP).

I tried to simulate this in an JUnit test. The test contains an inner class which mocks the MainActivity as well as it sends the UDP call to the UdpListener:

public class UdpListener extends Thread implements Subject {
    private DatagramSocket serverSocket;
    private DatagramPacket receivedPacket;
    private boolean running = false;
    private String sentence = "";

    private Observer observer;

    private static final String TAG = "UdpListener";

    public UdpListener(Observer o) throws SocketException {
        serverSocket = new DatagramSocket(9800);
        setRunning(true);

        observer = o;
    }

    @Override
    public void run() {
        setName(TAG);
        while (isRunning())  {
            byte[] receivedData = new byte[1024];
            receivedPacket = new DatagramPacket(receivedData, receivedData.length);
            try {
                serverSocket.receive(receivedPacket);
            } 
            catch (IOException e) {
                Log.w(TAG, e.getMessage());
            }

            try {
                sentence = new String(receivedPacket.getData(), 0, receivedPacket.getLength(), "UTF-8");
                if ("UPDATE".equals(sentence))  {
                    notifyObserver();
                }
            } 
            catch (UnsupportedEncodingException e) {
                Log.w(TAG, e.getMessage());
            }
        }
    }

    private boolean isRunning() {
        return running;
    }

    public void setRunning(boolean running) {
        this.running = running;
    }

    @Override
    public void notifyObserver() {
        observer.update();
    }
}

This is the corresponding test:

@RunWith(RobolectricTestRunner.class)
public class UdpListenerTest {

    private MainActivityMock mainActivityMock = new MainActivityMock();

    @Before
    public void setUp() throws Exception {
        mainActivityMock.setUpdate(false);
    }

    @After
    public void tearDown() throws Exception {
        mainActivityMock.setUpdate(false);
    }

    @Test
    public void canNotifyObserver() throws IOException, InterruptedException {
        UdpListener udpListener = new UdpListener(mainActivityMock);
        udpListener.setRunning(true);
        udpListener.start();    

        InetAddress ipAddress = InetAddress.getByName("localhost");
        DatagramSocket datagramSocket = new DatagramSocket();
        DatagramPacket sendPacket = new DatagramPacket("UPDATE".getBytes(), "UPDATE".length(), ipAddress, 9800);
        datagramSocket.send(sendPacket);
        datagramSocket.close();

        assertTrue(mainActivityMock.isUpdate());

        udpListener.setRunning(false);
    }

    private class MainActivityMock implements Observer {

        private boolean update = false;

        @Override
        public void update() {
            update = true;
        }

        public boolean isUpdate()  {
            return update;
        }

        public void setUpdate(boolean update)  {
            this.update = update;
        }
    }
}

The good thing is that my concept works. But, this test doesn’t. That means it only does when I stop with a breakpoint at this line datagramSocket.close(); and wait for about a second. Why this happens is clear. But how can I do that automatically? I thought about using wait() but I have to invoke notify() from the other thread for that. The same problem with CountDownLatch. I’m not sure how to solve that without changing UdpListener.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T04:11:42+00:00Added an answer on May 28, 2026 at 4:11 am

    You could write a simple loop with a specified timeout.

    try {
      long timeout = 500; // ms
      long lastTime = System.currentTimeMillis();
      while(timeout > 0 && !mainActivityMock.isUpdate()) {
        Thread.sleep(timeout);
        timeout -= System.currentTimeMillis() - lastTime;
        lastTime = System.currentTimeMillis();
      }
    } catch(InterruptedException e) {
    
    } finally {
      assertTrue(mainActivityMock.isUpdate());
    }
    

    By the way – you should declare your running attribute to volatile.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've got an Android app which has a periodic background Service. I want this
I'm writing an Android app where users can upload video to Youtube. I'd like
I have an Android app that should open links sent via email. I only
I have the following menu layout in my Android app: <?xml version=1.0 encoding=utf-8?> <menu
I am writing a simple android app which have a edittext and a button.
Hi I am developing an android app which is accessed by entering by a
The user of my Android app should be enabled to post a message to
I would like to develop an android application with the following description: The app
For an Android app, I have the following functionality private ArrayList<String> _categories; // eg
I had created a small app such that the image which is displaying should

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.