Android OSで単純なクライアントソケットを作成しようとしていて、ウェブ上で素材を検索しているときに、いくつかのエラーがあり、無限ループですが、単純な例としてその仕事をしています)、私は理解できないコードの部分を持っているので、このコミュニティが私を助けて、この全リスナー部分がなぜ存在し、何が目的はそれを果たすのか?コード例のリスナーポイント
public interface OnListener {
void listenerMethod(String text);//never invoked pretty much
}
public class ClientTask extends AsyncTask<String, String, String> implements OnListener {
@Override
public void listenerMethod(String text) {//this gets executed after send(View v) method, 'text' String variable contains the msgToSend from phone (from textfield above SEND button)
sendMessage(text);//invoked by onStop with String variable == "bye"... and it gets stucked in a loop at this point
}
}
private ClientTask myClientTask;
private OnListener listener;
public void addListener(OnListener listenerToAdd) {//this method is invoked by send(View v)
this.listener = listenerToAdd;
}
public void send(View v) {//invoked when you press the Send button, empty strings do not get sent (they stop at a trycatch and don't execute any network thingies)
addListener(myClientTask);//why does it add listener each time a msg is sent?
if (listener != null)
listener.listenerMethod(((EditText) findViewById(R.id.editText_MsgToSend)) //this here gets the msg you typed into the editable textfield above SEND button
.getText().toString());
}
@Override
protected void onStop() {//Restart button invokes this
try {
if (listener != null)
listener.listenerMethod("bye");
clientSocket.close();
} catch (Exception e) {
// TODO: handle exception
}
super.onStop();
}
Androidサークルでは非常に一般的ですが、インターフェイスを実装するクラスであるインターフェイスコールバックは、インターフェイスに緊密にバインドされているクラスに渡され、実装されたクラスにメッセージが送信されます。 – t0mm13b