how to run TimerTask off main UI thread?

Posted by huskyd97 on Stack Overflow See other posts from Stack Overflow or by huskyd97
Published on 2014-06-13T03:21:54Z Indexed on 2014/06/13 3:24 UTC
Read the original article Hit count: 180

Filed under:
|
|

I am having trouble with a TimerTask Interfering with In App Purchasing (Async Tasks). I am weak with Threads, so I believe it is running on the main UI thread, eating up resources. How can I run this outside the UI thread? I have searched, and tried some suggestions using handlers. but seems like I get the same result, app gets really laggy. when I don't run this task (refreshes every 500mS), the activity runs smoothly, and there are no hangs during In app purchases. Your help is appreciated, code snippet below:

public class DummyButtonClickerActivity extends Activity {

        protected Timer timeTicker = new Timer("Ticker");
        private Handler timerHandler = new Handler();
        protected int timeTickDown = 20;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainhd);

    // start money earned timer handler
    TimerTask tick = new TimerTask() {
        public void run() {
            myTickTask();
        }
    }; 

    timeTicker.scheduleAtFixedRate(tick, 0, 500); // 500 ms each


} // End OnCreate



protected void myTickTask() {

    if (timeTickDown == 0) {

        /// run my code here
        //total = total + _Rate;





        timerHandler.post(doUpdateTimeout);
}
      else if(timeTickDown < 0) {
        // do nothing
    }

    timeTickDown--;

}

private Runnable doUpdateTimeout = new Runnable() {
    public void run() {

        updateTimeout();
    }
};



private void updateTimeout() {

    // reset tick
    timeTickDown = 2; // 2* 500ms == once a second



}

}

© Stack Overflow or respective owner

Related posts about java

Related posts about android