开发者

android call an outside function from a thread

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 cl开发者_运维技巧ass 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜