I\'m developing an android application, and I have a button which starts/pauses certain simulation process. While this process is running, I need to output some data from it
You can solve the problem with android.os.Handler. Handler instance is bound to the thread that creates it, you can post Runnables to it and it will execute them in the thread it is bound to. For example:
import android.os.Handler;
import android.widget.TextView;
public class MyActivity extends Activity {
private Handler uiHandler;
private TextView simulationStatus;
@Override
public void onCreate(Bundle savedInstanceState) {
...
uiHandler = new Handler();
...
simulationStatus = (TextView) findViewById(R.id.simulationStatus);
...
}
// This method is to be executed on the simulation thread.
public void simulate() {
...
final String simulationStatusText = ...;
...
uiHandler.post(new Runnable() {
@Override
public void run() {
// This is run on the UI thread.
simulationStatus.setText(simulationStatusText);
...
}
});
}
...
}
You can also use AsyncTask. See the link for example.
Pass the activity to your thread, and use it from within to access your views.
// from your activity:
myExternalThread = new MyCustomCode(this); // <-- activity passed
// your "simulation process" constructor:
public MyCustomCode(Activity parent) {
this.parent = parent;
}
// and when you want to access views:
parent.runOnUiThread(new Runnable() {
@Override
public void run() {
parent.findViewById(R.id.text_view);
... do something to your UI ...
}
});
My preferred way of creating these external tasks is to use AsyncTask
(then you don't have to worry about runOnUiThread
, among other benefits). I don't know if it applies to your case, but you should check it out.
You can handle it in many ways,
Try to use AsyncTask in this, your background work done in doInBackGround() method, and your UI will not block and you can also access the views of Activity from where you call AsyncTask by its context via publishProgress() and onProgressUpdate() .
If you are using a simple Thread then using Handler or message or runOnUiThread you can update the view of main thread.
but, in your way I think AsyncTask is best for you.
you have to store the data which you are wanting do show into a public var and let your Thread call a Runnable via Handler.post(runnable) The code in the run() method of the Runnable is able to access the Textview
They can be accessed but only read-only. What you mean is you want to trigger changes from a thread on the views. From the worker thread (non-UI) these changes cannot be triggered, you need to use .runOnUiThread()
or use Handlers
. Use these at the point where you want to show something, e.g update the textview in .runOnUiThread(),
Example:
myThread = new Thread()
{
@Override
public void run() {
//yourOperation
MyActivity.this.runOnUiThread(new Runnable(){
@Override
public void run() {
if(e!=null)
{
myTextView.setText("something");
}
}});
super.run();
}
};
myThread.start();