How can i send a message between an activity and a thread if put the thread in a class?
Okay, here is a little more detailed code:
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;
}
}
The following class is not a part of 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();
}
}
This is my Activity:
Modified thread:
In the constructor i can store UI thread’s messagehandler.