Search code examples
androidobserver-patternandroid-2.1-eclair

How can I update my UI using an observer?


I've implemented a simple Observer pattern in a "hello world" style app.

I've got 2 buttons, which call onStart() and onDestroy() on a Service.

In the onStart() I register an observer and then get my observer to run a for loop calling observe.update() once every second for 10 seconds. This in turn calls an update() method in my service.

I'm trying to display some dummy data which gets returned, but I'm getting the following error :

11-26 23:21:12.829: ERROR/AndroidRuntime(676): FATAL EXCEPTION: Thread-8
        java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:121)
        at android.widget.Toast.<init>(Toast.java:68)
        at android.widget.Toast.makeText(Toast.java:231)
        at com.jameselsey.observerpattern.LocalService.observe(LocalService.java:27)
        at obs.Stub$1.run(Stub.java:49)
        at java.lang.Thread.run(Thread.java:1096)

I'm doing the following in my service :

public void observe(String message)
    {
        Context context = getApplicationContext();
        Log.d("TEST", "Inside observe() on service, value is " + message);

        Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
        toast.show();
    }

After a bit of research, it seems I can't create a Toast message as this method doesn't run on the main UI thread.

Is there anyway I can spit out message onto my UI? I'm just looking to have it display on the activitiy, even a regular textView is OK.


Solution

  • Services are not supposed to show any UI. The only acceptable approach is to display a notification which can start an activity through an intent. Your service can also communicate with your UI using a BroadcastReceiver or it can start an activity directly.

    If somehow your activity gets called on a background thread, you can get it running on the main thread using runOnUiThread. You should also get intimately familiar with services in general.