2017-08-08 15 views
1

Dear。私はAndroidの開発を勉強しています。私はHandlers/LoopersとMessageQueueに固執しています。 は、ドキュメントによると、ハンドラは、別のスレッドへのsendMessageとポスト(Runnableを)することができますので、私は次のことを試してみた:ハンドラーを使用してAndroidでsendMessageを送信する

public class MyThread extends Thread { 
    public MyThread(String argument) { 
     //save the arguments to some member attribute 
    } 

    @Override 
    public void run() { 
     //calculate something 
     String result = doSomething(); 

     //now I need send this result to the MainActivity. 
     //Ive tried this 
     Bundle bundle = new Bundle(); 
     bundle.putString("someKey", result); 
     Message msg = Message.obtain(); 
     msg.what = 2; 
     msg.setData(bundle); 

     //I hope this could access the Main Thread message queue 
     new Handler(Looper.getMainLooper()).sendMessage(msg); 
    } 
} 

私は2つのjavaファイルが、別のクラスのための1つを持っていますそして、私の主な活動:私はそれは本当に例やドキュメントを読んでどのように動作するかを理解することができませんでしたので

public class MainActivity extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstance) { 
     //super and inflate the layout 
     //use findViewById to get some View 
    } 

    //I think this could access the same MessageQueue as the thread did 
    private Handler mHandler = new Hander() { 
     @Override 
     public void handleMessage(Message msg) { 
      if (msg.what == 2) { 
       //I thought the sendMessage invoked inside the Thread 
       //would go here, where I can process the bundle and 
       //set some data to a View element and not only Thread change 
      } 
     } 
    } 
} 

、私は知らないスレッド(からいくつかのデータを得ることができる方法で簡単に説明したいと思いますMainActivity)をintに表示するoアクティビティーまたはフラグメント内のビュー。あなたの例では

おかげ

+0

MyThreadを開始した場所 – Rahul

+0

現在、ボタンのonClickをMainActivity内に配置しています。 –

答えて

1

についての詳細を読むことができます。それがMainActivityであなたが戻ってきた理由ではありません。

MyThreadでmHandlerの参照を取得し、その上でsendMessage()を呼び出すことができます。このようにして、自分の仕事にシングルハンドラを使用しています。

+0

あなたはそうです。私は、メインスレッドがすでにそれ自身の暗黙のハンドラを持っていることを理解しました。 MainLooperを渡す新しいスレッド(スレッド内)を作成しても、すでにMainThreadにバインドされているハンドラと同じハンドラではありません。 これを解決するには、MainThreadハンドラをMyThreadに渡してメッセージを送信する必要がありました。 ご説明いただきありがとうございます。 –

0

がメインでLooper.getMainLooper()で、これはあなたのケースでは、MainActivityは、UIスレッドで実行されていると、それがハンドラを持っている、UIスレッドに取り付けられている。Handlerにメッセージを送信することを意味しますHandlerという名前になりますので、メッセージはhandleMessageで受信します。

あなたは、私は基本的に、あなたの実装からUIスレッド上の2つのハンドラを作成したと思いますLooperCommunicating with the UI ThreadHandler

関連する問題