views:

65

answers:

2

Greetings.

How can I send two parameters into a thread and run methods when the user pushes buttons on the display. Having my variables in the UI thread didn't work and were erased when the UI thread randomly restarts.

UI Thread ______________ Other Thread

User presses button -------> Run Method

Cheers.

A: 

I think you should just define listeners for your buttons. And those listeners should in turn, launch threads with the paremeters you want, to perform other tasks, while keeping the UI available and responsible to the user again, while those threads are performed. You need something like this:

public void onClick(View v) {
  new Thread(new Runnable() {
    public void run() {
      Bitmap b = loadImageFromNetwork();
      mImageView.setImageBitmap(b);
    }
  }).start();
}

This example was taken from the Android Developers Blog, where you can get other helpful information and hints.

Luis Miguel
That will not work because the variables will still be nulled when the screen orientation changes.
Mitchell
You didn't mention screen orientation change in your post. It is not something I have dealt with yet, but eventually, if some method is called when the screen orientation changes, you can use it to save variables of importance and/or apply a locker to an object used by the threads if you need to stop their activity temporarily, or signal them that change.
Luis Miguel
+1  A: 

Have a look at this blog article. It describes how to keep a thread working across screen rotation.

Flo