如何在活動和線程之間發送消息(如果將線程放入類中)?線程(在類中)和活動之間的Android消息傳遞
好,這裏是一個小更詳細的代碼:
public class AnActivity extends Activity implements OnClickListener, Callback
{
Button b = null;
TextView t = null;
MyThread mThread = null;
public Handler mainHandler = new Handler(this);
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = (Button) findViewById(R.id.buttonSEND);
b.setOnClickListener(this);
mThread = new MyThread(this);
mThread.start();
}
@Override
public void onClick(View v)
{
Message m = Message.obtain();
m.what = 4;
mThread.myThreadHandler.sendMessage(m);
}
@Override
public boolean handleMessage(Message msg)
{
Toast.makeText(this, "What= " + Integer.toString(msg.what), Toast.LENGTH_SHORT).show();
return false;
}
}
下面的類是不AnActivity
public class MyThread extends Thread
{
public Handler myThreadHandler;
Activity mainActivity;
public MyThread (AnActivity anActivity)
{
this.mainActivity = anActivity;
}
@Override
public void run()
{
Looper.prepare();
myThreadHandler = new Handler()
{
// sending back a message immediately after a received one
public void handleMessage(Message msg)
{
Message m = Message.obtain();
m.what = 10;
// MY PROBLEM:
// mainActivity.mainHandler.sendMessage(m); // mainHandler is not visible
// mainActivity.sendMessage(m); // does not working
}
};
Looper.loop();
}
}
謝謝,但這是一個不同的問題。 – TTSilver