问题
Good day to you all. I'm experiencing quite an issue right now with my simple Android application.
The 2 main elements I have are a bound Service and a main Activity. I want the Activity to display (through TextViews) the fact that the Service found something. To do so, I declare a Listener interface within the Service, handle a list of listeners registered to him and notify the listeners with a specific method.
MyService
void notifyNewElement(){
for (Listener listener : listeners) {
listener.handleNewElement(this);
}
}
public interface Listener {
void handleNewElement(MyService sender);
}
private List<Listener> listeners = new ArrayList<Listener>();
public void addListener(Listener listener) {
this.listeners.add(listener);
}
public void removeListener(Listener listener) {
this.listeners.remove(listener);
}
MainActivity
buttonStart.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
registerListener();
}
});
buttonStop.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
unresgisterListener();
}
});
void registerListener(){
tService.addListener(this);
}
void unresgisterListener(){
tService.removeListener(this);
}
public void handleNewElement(MyService sender) {
Log.d("NEW_ELEM","new element found");
message_box.setText("new element found");
}
I ofcourse recovered the TextViews and such in the Activity, I don't have to show the code here as I know everything's fine on that side. As you can see in the last method, the Log.d() works fine, the method is really triggered. But when I want to update the TextView, the Activity can't do it PLUS the service stops doing his calculations. As funny as it could be, if I unregister the listener and register it again (through the 2 buttons you can see in the Activity), the Service calculations don't get stopped anymore when triggering handleNewElement, yet the TextView is still not updated (it just doesn't block anymore).
I used exactly the same setup in another application and it worked like a charm :/
If you guys have any idea of what could be the cause of all that trouble, it'd be wonderful for you to share it !
Thanks in advance.
回答1:
public void handleNewElement(MyService sender) {
Log.d("NEW_ELEM","new element found");
runOnUiThread(new Runnable(){
public void run(){
message_box.setText("new element found");
}
});
}
来源:https://stackoverflow.com/questions/13306221/listener-method-interface-in-service-in-my-activity-doesnt-want-to-display-a