我是android的新手,需要帮助将空心代码转换为实时更新图,其中显示了ecg跟踪。 让我们现在使用正弦曲线。所以我需要一个显示移动正弦图的图表。 现在我只是一个使用aChartEngine插件显示静态图的简单代码。 使用可扩展模式(线程/ asynctask)实现移动(实时更新)图的最简单方法是什么?
public class LiveView extends Activity {
Button startTimer;
TextView heartRate, battery;
LinearLayout lineGraphLayout;
View lineGraph;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.liveview);
startTimer = (Button) findViewById(R.id.bStartTimer);
heartRate = (TextView) findViewById(R.id.tvHeartRate);
battery = (TextView) findViewById(R.id.tvBatteryLevel);
lineGraphLayout = (LinearLayout) findViewById(R.id.lineGraph);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (lineGraph == null) {
// sample Values
lineGraph = getLineGraphView();
lineGraphLayout.addView(lineGraph);
} else
((GraphicalView) lineGraph).repaint();
}
private View getLineGraphView() {
int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // x values!
int[] y = { 30, 34, 45, 57, 77, -89, 100, 111, 123, 145 };
TimeSeries series = new TimeSeries("Lead 1");
for (int i = 0; i < x.length; i++)
series.add(x[i], y[i]);
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(series);
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
XYSeriesRenderer renderer = new XYSeriesRenderer();
mRenderer.addSeriesRenderer(renderer);
View tempView = ChartFactory.getLineChartView(this, dataset, mRenderer);
tempView.setBackgroundColor(Color.WHITE);
return tempView;
}
}
我尝试使用TimerTask ......但应用程序只是挂起了!
public void toCallAsynchronous() {
TimerTask doAsynchronousTask;
final Handler handler = new Handler();
Timer timer = new Timer();
doAsynchronousTask = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
handler.post(new Runnable() {
public void run() {
if (isRunning) {
try {
lineGraph = getLineGraphView();
lineGraphLayout.addView(lineGraph);
((GraphicalView) lineGraph).repaint();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 50);// execute in every 500
// ms
答案 0 :(得分:1)
我认为Handler
优于AsycTask
或此处的线索。处理程序直接在UI线程上运行,易于实现:
public class LiveView extends Activity {
//...
RefreshHandler handler = new RefreshHandler();
class RefreshHandler extends Handler {
@Override
public void handleMessage(Message msg) {
// Update your graph here
sendMessageDelayed(obtainMessage(0), 500); // next update in 500 ms
}
}
}
要开始实时更新,请在代码中的某处调用handler.sendMessage(handler.obtainMessage(0));
。