简体   繁体   English

不断将数据传递给AsyncTask吗?

[英]Continuously pass in data to AsyncTask?

In my Android app, I have a snippet of code, similar to Run code for x seconds in Java? 在我的Android应用中,我有一小段代码,类似于在Java中运行代码x秒钟?

long t= System.currentTimeMillis();
long end = t+15000;
while(System.currentTimeMillis() < end) {
//useful calculation
}

And this code will freeze the UI thread, so I'm wondering if there's a way to continuously pass in data to my AsyncTask that will do the calculation in the background thread to avoid freezing? 并且此代码将冻结UI线程,所以我想知道是否有一种方法可以将数据连续传递到AsyncTask中,该方法将在后台线程中进行计算以避免冻结? Or is there a better way, or to keep calling AsyncTask from within my while loop? 还是有更好的方法,还是在我的while循环内不断调用AsyncTask?

For this purpose, use a Handler instead. 为此,请改用Handler。

It goes like this : 它是这样的:

Handler timerHandler = new Handler();

Runnable timerRunnable = new Runnable() {

    @Override
    public void run() {
        //READ HERE WHAT YOU NEED FROM THE SENSOR (useful calculation)

        //And then set the next execution of the sensor reading
        timerHandler.postDelayed(this, 1000); //runs 1000 milliseconds
    }
};

//Launch It for the first time
timerHandler.post(timerRunnable);

//Whenever you would like to stop it, use the following commented line
//timerHandler.removeCallbacks(timerRunnable);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM