2016-05-24 7 views
0

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(); 
} 
+0

Androidサークルでは非常に一般的ですが、インターフェイスを実装するクラスであるインターフェイスコールバックは、インターフェイスに緊密にバインドされているクラスに渡され、実装されたクラスにメッセージが送信されます。 – t0mm13b

答えて

0

これは、コールバックパターンで、ハリウッドの原則は「私はあなたを呼んでよ、私を呼んではいけない」: は、ここにそのリスナーに関するコードの一部です。まず、クラスClientTaskが実装し実装するためのインタフェースOnListenerを定義します。これで、ClientTaskはClientTaskクラス型とOnListener型の両方になりました。それはそのインターフェイスを実装しているのでaddListenerメソッドは、単にタイプOnListenerであるClientTaskを通過することが可能となり、それは我々が我々だけでlistener.listenerMethod(EditText...blah)を呼び出す

listenerMethod(String string)

その後メソッドの実装へのアクセスを持っていることを意味しています編集テキスト内の任意の文字列を取り、OnListenerを実装するクラスに移動します(この例ではClientTask)。EditTextにある文字列でメッセージを送信します。

したがって、send(View v) ClientTask内のlistenerMethod(String text)も実行されます。

+0

私はこのコードをステップバイステップでデバッグした後に何が実行されるのか理解していますが、私が理解しようとしているのはその目的です。何がポイントなのですが、なぜメッセージが送信されるたびに 'addListener'が必要なのでしょうか?それは何を助けますか?タスクのための新しいスレッドを実装するのは何か?なぜ、そのリスナー部分全体をスキップして、すぐに 'sendMessage(text) 'を呼び出すことができないのですか? – Amai

+0

ソケットはデータのストリームを送信する接続です。したがって、必ず同じメッセージではないものを送信します –