views:

293

answers:

2

hi.. say for example I have this code in my activity:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);   
    Thread cThread = new Thread(new Runner());
    cThread.start();
}

private NotifyMe(){
    //do something here
}

and this is my Runner class:

public class TCPClient implements Runnable {
   public void run(){
      //call NotifyMe() [THIS IS MY QUESTION]
   }
}

I have a thread on my activity that runs the Runner Class. Once the thread start, I would like to call the NotifyMe() function that is located at the activity. Is this possible? Please let me know if you don't understand my question. Thanks in advance.

+1  A: 

You can add a Constructor to the TCPClient that takes a reference to the activity, change the notifyMe method to public and then call the notifyMe method on the activity object that is stored in the thread.

The problem you would get with this is that activities may be closed, paused, destroyed while your thread is running. To check if the activity is still active use the isFinishing() method from the activity.

This solution is somewhat dangerous if your activity uses a lot of memory because the reference to the activity in the thread will let the garbage collector not reclaim the memory used by the drawables of the UI in the activity etc. until the thread is executed and can be garbage collected as well. If your activity is not that heavy in memory that should be ok. If it is or if you want to access the data from the thread from multiple activities have a look at this question.

A more or less unrelated note if you have a very small thread that won't run the whole time your app is running use a AsyncTask. This will allow you to simply put a single operation into the background.

Janusz
yup.. I followed your first suggestion and it is working for me. Thanks. If you don't mind, I would like to make a follow up question..In my NotifyMe() method, I tried to call Toast.maketext but it produces an exception.. java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare(). ..What causes this Exception? But if I remove Toast.maketext, it doesn't cause a problem.
junmats
Create a new question for this (link to this question if you need if for clarification) and post the link back here then I or somebody else can answer it in an appropriate way
Janusz
A: 

Hi, How to print the value of increasing thread objects?

Asma-ull-Hosna