Attivazione di un brindisi da un ascoltatore
Domanda
sto usando un pacchetto esterno definendo un JunctionActor. L'idea è che un JunctionActor può inviare messaggi JSON a un server remoto tramite un metodo chiamato sendMessage e ricevere messaggi tramite un ascoltatore chiamando onMessageReceived. Nella mia realizzazione, il dispositivo riceve ogni messaggio che invia, rimettendo così onMessageReceived. Eppure, nel mio codice, ho incluso un oggetto ChatClient nella mia classe di attività, che deve chiamare il metodo show_message. show_message innesca un brindisi. Quando sto chiamando da show_message ONJOIN, non v'è alcun problema a tutti, ma quando si chiama da onMessageReceived, non mostra nulla in su, mentre il mio debugger mi dice che l'applicazione riceve infatti un messaggio e che onMessageReceived viene attivato. Nel frattempo, il richiamo della show_message nel metodo ONJOIN effettivamente funziona. E non riesco a vedere alcuna differenza tra ciascuno di essi. Avete una soluzione?
Grazie mille
public class HelloWorldJunctionActivity extends Activity {
onCreate(...){...} [...]
private class ChatClient extends JunctionActor {
public ChatClient() {
super("client");
}
public void onActivityJoin() {
show_message("Connected");
}
@Override
public void onMessageReceived(MessageHeader header, JSONObject msg) {
try {
show_message(msg.getString("text"));
} catch (JSONException e) {
// TODO Auto-generated catch block
show_message(e.getMessage());
}
}
}
void show_message(String message) {
Toast
.makeText(HelloWorldJunctionActivity.this, message, Toast.LENGTH_SHORT)
.show();
}
}
Soluzione
I'm not sure how JunctionActor works, but is it possible that the onMessageReceived callback is invoked from a thread which is not the UI thread? If that's the case you might have to use a Handler, as explained in this post.
Altri suggerimenti
The reason it is not toasting is because the context object HelloWorldJunctionActivity.this is non existent. Try sending the context object as well
void show_message(String message, Context con) { Toast .makeText(con, message, Toast.LENGTH_SHORT) .show(); } }
show_message("Connected", getApplicationContext());