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アクティビティーまたはフラグメント内のビュー。あなたの例では
おかげ
MyThreadを開始した場所 – Rahul
現在、ボタンのonClickをMainActivity内に配置しています。 –