stu*_*u90 6 android android-asynctask
我是Android应用程序开发的新手,并且遇到了Async任务的问题.所以我正在尝试创建一个ECG图形应用程序,在图形发生时进行一些后台处理.
我已经定义了以下异步任务 -
private class Erosion extends AsyncTask <Void,Void,Void> {
@Override
protected Void doInBackground(Void...unused ) {
int i,tempIndex;
double[] tempArray = new double[13];
double min = ecgSamples[ecgSampleForErosionIndex] - gArray[0];
while (ecgIncoming)
{
if (ecgSampleForErosionIndex > 179999)
{
ecgSampleForErosionIndex = 0;
}
for(i= 0;i<13;i++)
{
tempIndex = ecgSampleForErosionIndex + i;
if (tempIndex > 179999)
{
tempIndex = (ecgSampleForErosionIndex + i) - 180000;
}
tempArray[i] = ecgSamples[tempIndex] - gArray[i];
if (tempArray[i] < min)
{
min = tempArray[i];
}
}
//min needs to be stored in the erosionFirst Array
if (erosionFirstArrayIndex > 179999)
{
erosionFirstArrayIndex = 0;
}
ecgErosion[erosionFirstArrayIndex] = min;
erosionFirstArrayIndex++;
ecgSampleForErosionIndex++;
}
return null;
}
} //End of Async Task
Run Code Online (Sandbox Code Playgroud)
所以我要做的就是在异步任务中修改特定数组的内容 - 我不需要更新UI(至少现在不需要)
但是,当我运行此异步任务时,我的ECG图形会变慢并变得不稳定.当我注释掉"new Erosion().execute();"时 在我启动异步任务的代码中,图形再次变为正常.
是不是异步任务应该在一个单独的线程上,所以不影响我的UI线程上发生的事情?我究竟做错了什么?
即使您在后台线程上运行了大量代码,它仍然会影响设备的CPU负载,因此也可能导致UI线程延迟,特别是如果设备具有单核CPU.
看起来你在doInBackground方法中有一个非常繁重的循环,它不断运行并且只使用CPU不间断,这会使它过载.我不确定这个循环是什么,但如果它不必不断刷新你可能想考虑添加一个线程睡眠,允许其他线程获得更多的CPU时间:
while (ecgIncoming)
{
... do your thing ...
Thread.sleep(100); // wait for 100 milliseconds before running another loop
}
Run Code Online (Sandbox Code Playgroud)
显然,"100"只是一个数字,如果数组可以每秒更新一次,使其成为1000,等等......
| 归档时间: |
|
| 查看次数: |
4699 次 |
| 最近记录: |