3

The documentation says that execute() must be called from a UI thread. But, since I am updating images every few seconds, I am using a Runnable. And in that, I define the operations that have to be executed. Starting(execute())ASyncTask is one of them. But, since ASyncTask is not supposed to be called from anything but the UI thread, how do I proceed?

Namratha
  • 16,630
  • 27
  • 90
  • 125

3 Answers3

5

just add runOnUiThread in Runnable for starting AsyncTask :

private Runnable updateImages= new Runnable() {
    public void run() {
        runOnUiThread(new Runnable() {
            public void run() { 
                // call your asynctask here 
            }
        }
    });
    //////YOUR CODE HERE
}
arbel03
  • 1,217
  • 2
  • 14
  • 24
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
  • You almost have to put that runOnUiThread in a conditional, or it will slow down your entire program – Jack Satriano Jun 28 '12 at 06:09
  • Can I do a sendMessage instead of runOnUiThread and then since the Handler's implemented on the UI thread, I will handle the message i.e. start the ASyncTask there. – Namratha Jul 06 '12 at 08:21
  • @Namratha : `runOnUiThread` also implemented on the UI thread. `runOnUiThread` is method of Activity class not from any thread. i suggest `runOnUiThread` because it's easy to implement. – ρяσѕρєя K Jul 06 '12 at 08:26
  • @Namratha : if you have any issue in implementing `runOnUiThread` or Updating UI from `runOnUiThread` then tell me i will try to help u.Thanks – ρяσѕρєя K Jul 06 '12 at 08:27
  • 1
    @imrankhan: Yes, I got that. I just wanted to know the advantages/disadvantages of noth the methods. Thanks! – Namratha Jul 06 '12 at 08:50
1

Possibly redesign your project to work with only AsyncTasks rather than a Runnable. I'm not sure how AsyncTask likes this behavior as well, but I have changed some UI stuff in AsyncTasks before.

Jack Satriano
  • 1,999
  • 1
  • 13
  • 17
0

Here you go.

private Handler mHandler = new Handler(Looper.getMainLooper());

private Runnable updateImages= new Runnable() {
    public void run() {
        .........
        .........
        ......... 

        mHandler.post(new Runnable() {
            public void run() {
               call your asynctask here
            }
        });
    }
};
Vipul
  • 27,808
  • 7
  • 60
  • 75
  • But it's not on the main thread. Has this worked for you? This is against what the documentation says. – Namratha Jul 06 '12 at 08:22