CluelessAnrdoidDev
CluelessAnrdoidDev

Reputation: 13

Android Service upding UI with timer crashing

So I'm trying to update an overlay with a timer however it always crashes. I read something about UI thread but I'm kinda lost on what that even means.

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

    WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
    overlayView.getBackground().setAlpha(50);
    windowManager.addView(overlayView, params);

    new Thread(new Runnable() {
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //crashing here//
                overlayView.getBackground().setAlpha(150);
                //testing if updating
                counter = counter + 1;
                notification.setContentText("number" + counter);
                startForeground(1, notification.build());
            }

        }
    }).start();


    return START_NOT_STICKY;
}

It always returns this error:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

Upvotes: 1

Views: 86

Answers (1)

Fartab
Fartab

Reputation: 5493

Android do not allow updating UI from any thread except UI/Main thread. I see you have created a new Thread so your updating UI stuff is on a worker thread which is not allowed in Android.

A simple solution is to create a handler of main thread and post a runnable to it.

new Handler(Looper.getMainLooper()).post(new Runnable() {
       public void run() {
            // modify UI here
            // overlayView.getBackground().setAlpha(150);
       }
});

Upvotes: 1

Related Questions