Note that there are some explanatory texts on larger screens.

plurals
  1. POAndroid: TimerTask scheduled for repetition getting fired only once
    primarykey
    data
    text
    <p>Ok this is a very weird problem I am having, and I'm pretty sure that I am messing up somewhere, but I can't quite figure out where.</p> <p>What I am trying is - </p> <ul> <li>Schedule a <code>Timer</code> to execute a <code>TimerTask</code> every five seconds</li> <li>The <code>TimerTask</code> in turn executes an <code>AsyncTask</code> (which in this case simple sleeps for a second before returning the static count of the number of AsyncTasks).</li> <li>Finally, the aforementioned count is updated in the UI.</li> </ul> <p>And of course, the appropriate <code>Handler</code>s and <code>Runnable</code>s have been used to post asynchronous messages from other threads to the UI.</p> <p>This code executes only once. I expect it to fire every 5 seconds. Here's the code. </p> <p><em><strong>Note:</em></strong> I had no idea what to do with the <code>Looper</code>. I put it there after trial and error!</p> <pre><code>public class TimerAsyncMixActivity extends Activity { public static final String TAG = "TimerAsyncMix"; static int executionCount = 0; Handler mHandler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); new Timer().schedule(new MyTimerTask(this), 0, 5000); } class MyAsyncTask extends AsyncTask&lt;String, Void, Integer&gt;{ @Override protected Integer doInBackground(String... params) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ++executionCount; } @Override protected void onPostExecute(Integer result) { mHandler.post(new UpdateUiThread(TimerAsyncMixActivity.this, result)); super.onPostExecute(result); } } } class MyTimerTask extends TimerTask{ private TimerAsyncMixActivity tma; public MyTimerTask(TimerAsyncMixActivity tma) { this.tma = tma; } @Override public void run() { Looper.prepare(); Log.d(TimerAsyncMixActivity.TAG, "Timer task fired"); tma.new MyAsyncTask().execute(); Looper.loop(); Looper.myLooper().quit(); } } class UpdateUiThread implements Runnable{ int displayCount; TimerAsyncMixActivity tma; public UpdateUiThread(TimerAsyncMixActivity tma, int i) { this.displayCount = i; this.tma = tma; } @Override public void run() { TextView tv = (TextView) tma.findViewById(R.id.tvDisplay); tv.setText("Execution count is : "+displayCount); } </code></pre> <p>Can anyone point me to what I'm doing wrong?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload