Note that there are some explanatory texts on larger screens.

plurals
  1. POCalledFromWrongThreadException using Service IPC connection
    primarykey
    data
    text
    <p>I'm using the tutorial <a href="http://mindtherobot.com/blog/37/android-architecture-tutorial-developing-an-app-with-a-background-service-using-ipc/" rel="nofollow">here</a> to develop a Service that is (right now) just running a <code>TimerTask</code> to do <code>System.out.println("tick")</code> every second. My code is exactly like the code on the site, aside from some name changes. Everything works (the Service runs, outputs "tick") if I don't try to pass a String from the Service to the Activity.</p> <p><strong>What I'm trying to accomplish</strong> is to get a TextView in the main Activity to be updated with a String received from the Service. I have an <code>append(String)</code> method working fine that will update the TextView with new text. So in my Service's <code>TimerTask</code> I've added <code>listener.handleMessage("tick")</code> and my Activity implements the listener functionality:</p> <pre><code> public void handleMessage(String msg) throws RemoteException { append(msg); } </code></pre> <p>When I run the application, <code>System.out</code> shows a "tick", then a stacktrace with the <code>CalledFromWrongThreadException</code>, pointing to the <code>append()</code> method as the source of the problem.</p> <p>I know there's a few questions about this Exception, but most of them concern <code>Thread</code> and <code>Handler</code> issues; I couldn't find anything about Services. Anyone know if this is possible?</p> <h1>Solution</h1> <p>Extend Runnable:</p> <pre><code>class MyRunnable implements Runnable { private String msg; public MyRunnable(String msg) { this.msg = msg; } public void run() { appendNewline(msg); } } </code></pre> <p>and replace the callback with a call to global Handler:</p> <pre><code> public void handleMessage(String msg) throws RemoteException { handler.post(new MyRunnable(msg)); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload