Reputation: 7117
I have an IntentService which creates an Overlay with the help of a WindowManager. In the WindowManager I add a View which contains a ListView. Now I want to add a new Item to the ListView in the onHandleIntent Method but if I call
data.add("String");
adapter.notifyDataSetChanged();
the system throws an error
Only the original thread that created a view hierarchy can touch its views.
What can I do to prevent this?
Upvotes: 0
Views: 1118
Reputation: 9434
The screen may only be updated by the UI thread. A service cannot guarantee that it is running in the UI thread. Therefor a service may not update the screen directly.
The solution is to send a message to the UI thread. There are many ways to do this. Here is one:
In onCreate() for the Activity attached to the screen create a message handler:
mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message inputMessage) {
Update the UI here using data passed in the message.
}
}
Make mHandler available to the service (possibly via the intent used in StartService().
In the service send the a message to the handler:
Message msg = mHandler.obtainMessage(...);
... add info to msg as necessary
msg.sendToTarget();
These pages may help with the details:
http://developer.android.com/reference/android/os/Handler.html
and
http://developer.android.com/reference/android/os/Message.html
Upvotes: 1
Reputation: 6439
You could solve this by letting the Activity that holds the ListView to do the update. Activity.runOnUiThread() should do the job =]
Upvotes: 0