Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does runOnUiThread() not work inside Service?

Tags:

I am creating an application that needs to update values every minute even if the app isn't running.

Of course, I have set up a simple Service to do that. I have debug messages set up to tell me when the Service starts, when it updates (every minute), and when it closes. I also have a message telling me when the values update inside a runOnUiThread() method. All of my messages activate except for the one in the runOnUiThread(). Is there something I'm doing wrong (of course there is)? What do I need to change?

Code:

@Override
public void handleMessage(Message message) {

    try {

        if (!serviceStarted) {

            serviceStarted = true;
            serviceTest = true;

            while (serviceStarted) {

                new MainActivity().runOnUiThread(new Runnable() {

                    public void run() {

                            OverviewFragment.refresh(getApplicationContext());
                            System.out.println("yay");

                         }
                });

                Thread.sleep(((1 /* minutes */) * 60 * 1000));
                System.out.println("Updated values through service.");

            }
        }


    } catch (InterruptedException e) {

        Thread.currentThread().interrupt();
        e.printStackTrace();

    }

    stopSelf(message.arg1);
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!