2016-02-27 24 views
1

在我的Android应用程序,我有一小段代码,类似于Run code for x seconds in Java?不断传递数据给AsyncTask?

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

而这个代码将冻结UI线程,所以我不知道是否有在数据不断传递给我的AsyncTask方式那会在后台线程中进行计算以避免冻结?或者有更好的方法,或者继续在我的while循环中调用AsyncTask?

+0

听起来像是你想有一个主题,而不是一个的AsyncTask。如果某些事情应该在后台继续进行,则Thread更合适。 AsyncTasks在默认情况下在一个线程上运行,所以你不应该使用一个来处理超过几秒的处理。除此之外 - 你想通过什么样的数据,以什么频率?这样做的一种正常方式是通过同步消息队列。将数据传递给线程或任务是可能的,但容易出错。 –

+0

查看Android中的处理程序或服务类。 –

+0

@GabeSechan我正在以非常高的频率(至少对眼睛)从传感器读取数据(双倍),而不是手机上的传感器,我不确定是什么,但它看起来像10Hz ish。你能指给我一份文件吗? –

回答

0

为此,请使用Handler。

它是这样的:

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);