Android uses Achartengine to make dynamic ECG effects

Source: Internet
Author: User
Tags gettext

Achartengine is a very powerful charting engine, I have been exposed to the school, and use it to do a sensor application, think it is very long ago, today, the application of the source code for other people to study the engine.

The app works as follows:

gIthub Project address: Https://github.com/AlexZhuo/SensorMonitor

The main features of this app are as follows:

1, support mobile phone sensor number detection, support acceleration, magnetic field, distance and other sensor data real-time access

2. Using some third-party controls on GitHub to beautify the UI,

3. Support Full Screen display

4, through the old version of the Xutils 2 to achieve real-time database recording

5, through the POI to the database data exported to Excel, easy to analyze later.


Achartengine drawing based on pre-prepared data, that is, one frame at a time, if we want to dynamically generate a wave map and let the axis move with it is not difficult, it is only necessary to add data and refresh the view on the old data at intervals.

To use this icon engine in your project, Achartengine's jar package:

http://repository-achartengine.forge.cloudbees.com/snapshot/org/achartengine/achartengine/1.2.0/

Pay attention to the version, it may also be a new version later.

The following code to control the drawing, the principle is not very complex, GitHub has all the app code, if you like can also be on the original basis to help me perfect (students of the first online project, think of a little excitement).

Import Java.util.list;import Org.achartengine.chartfactory;import Org.achartengine.graphicalview;import Org.achartengine.chart.pointstyle;import Org.achartengine.model.xymultipleseriesdataset;import Org.achartengine.model.xyseries;import Org.achartengine.renderer.xymultipleseriesrenderer;import Org.achartengine.renderer.xyseriesrenderer;import Android.app.activity;import Android.content.Context;import Android.content.intent;import Android.graphics.color;import Android.graphics.paint.align;import Android.hardware.sensor;import Android.hardware.sensorevent;import Android.hardware.sensoreventlistener;import Android.hardware.sensormanager;import Android.os.bundle;import Android.os.handler;import android.os.Message; Import Android.os.vibrator;import Android.view.viewgroup.layoutparams;import Android.widget.linearlayout;import Android.widget.textview;import Com.lidroid.xutils.dbutils;import Com.lidroid.xutils.db.sqlite.selector;import Com.lidroid.xutils.exception.dbexception;import COM.SITU.MOdel. Accelerate_info;public class Accelactivity extends Activity{public sensormanager sensormanager;public Sensor Accelsensor; TextView XText; TextView Ytext; TextView Ztext; TextView Sumtext; TextView Danwei;  TextView Title;private Vibrator Vibrator; Sensoreventlistener Threeparamlistener; Sensoreventlistener Oneparamlistener; Sensoreventlistener Twoparamlistener; Handler Avghandler; Thread avgthread;int sensor_id = 0;//Chart related private Xyseries series; Private Xymultipleseriesdataset Mdataset; Private Graphicalview chart; Private Xymultipleseriesrenderer renderer; Private context context; private int yMax = 20;//y Axis maximum, according to different sensor changes private int xmax = 100;//One screen display measured number @overrideprotected void OnCreate (Bundle savedinst Ancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_accel); SensorManager = ( Sensormanager) Getsystemservice (sensor_service); avghandler = new Avehandler ();//Instantiate the control with an if (Xtext==null) {findviews ();} Intent Intent = getintent () Avgthread = new Thread (runnable);//Update average periodicallyThe value of the thread starts Avgthread.start ();//initializes each listener initlisteners (); Switch (WTD) {case Sensor.TYPE_ACCELEROMETER:title.setText ("Acceleration sensor");d Anwei.settext ("n/m^2"); accelsensor = Sensormanager.getdefaultsensor (Sensor.type_accelerometer); Sensormanager.registerlistener (ThreeParamListener,        Accelsensor, sensormanager.sensor_delay_ui); yMax = 20;sensor_id = 1;break;default:break;} Initialize the chart initchart ("*0.5s", Danwei.gettext (). toString (), 0,xmax,0,ymax);} /** * Fetch the function */private void Findviews () {xText = (TextView) Findviewbyid (R.id.xaxis) of the view text control; ytext = (TextView) Findviewby Id (r.id.yaxis); ztext = (TextView) Findviewbyid (r.id.zaxis); sumtext = (TextView) Findviewbyid (r.id.sum);d Anwei = ( TextView) Findviewbyid (r.id.danwei); title = (TextView) Findviewbyid (r.id.title);} /** * Initialize various listeners */private void Initlisteners () {threeparamlistener = new Sensoreventlistener () {// There are three listeners that return parameters @overridepublic void onsensorchanged (Sensorevent event) {//TODO auto-generated method Stubxtext.settext ( Event.values[0]+ ""); Ytext.settext (event.values[1]+ ""); Ztext.settext (event.values[2]+ ""); Double sum = Threedimentoone (Event.values[0], event.values[1], event.values[2]), Giveaverage (sum),//Writes the result of the current measurement to buffer , and then periodically find the average in buffer and show} @Overridepublic void onaccuracychanged (sensor sensor, int accuracy) {//TODO auto-generated Method stub}};} /** * Initialize chart */private void Initchart (String xtitle,string ytitle,int minx,int maxx,int miny,int maxy) {//Here get layout on main interface, below        The chart will be drawn in this layout. LinearLayout layout = (linearlayout) Findviewbyid (R.id.chart);        This class is used to place all points on the curve and is a collection of points, drawing the curve series = new Xyseries ("historical curve") according to these points;        Create an instance of a dataset that will be used to create the chart Mdataset = new Xymultipleseriesdataset ();                Add a set of points to the Mdataset.addseries (series) in this data set;        The following are settings for the style and properties of the curve, and renderer equivalent to a handle to render the chart int linecolor = Color.Black;        Pointstyle style = pointstyle.circle;              Renderer = Buildrenderer (LineColor, style, true); Set the style of the chart setchartsettings (renDerer, Xtitle,ytitle, MinX, MaxX,//x Axis min Max miny, Maxy,//y Axis min Max Color.Black,//Axis color colour color.               white//label color);                Generate Charts chart = Chartfactory.getlinechartview (this, mdataset, renderer); Add a chart to the layout go to Layout.addview (chart, new Layoutparams (Layoutparams.fill_parent, layoutparams.fill_parent));} @Overrideprotected void OnDestroy () {//TODO auto-generated method Stubsuper.ondestroy (); if (threeparamlistener!=null) {Sensormanager.unregisterlistener (threeparamlistener);} if (oneparamlistener!=null) {Sensormanager.unregisterlistener (oneparamlistener);} if (avgthread!=null) avgthread.interrupt ();D butils db = Dbutils.create (Getapplicationcontext ());//xutils frame try {List <Accelerate_info> list = Db.findall (Selector.from (Accelerate_info.class). WHERE ("sensor", "=", sensor_id));// See how much data System.out.println ("Quantity is" +list.size ()) written to the database altogether;} catch (Dbexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} /** * Modulus of summation vectors based on three coordinate vectors * @param x * @param y * @param z * @return */public static double Threedimentoone (double x,double y,double z) {return MATH.SQR T (x*x+y*y+z*z);} public int index = 0;//indicates how many data have been written for this time//where the length of the buffer can be set, for averaging double[] buffer = new double[500];//half a second for a maximum of 500 numbers public int I  Nterval = 500;//Average value per half second public double AVERAGE = 0;//Store Average/** * A sub-thread that calculates the average of the time at a fixed time and assigns textview */runnable = New Runnable () {@Overridepublic void Run () {//TODO auto-generated method StubSystem.out.println ("thread has started"); while (true) { try {thread.sleep (INTERVAL);//no fixed time averaging} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace (); avgthread = new Thread (runnable); Avgthread.start ();} if (index!=0) {Double sum = 0;for (int i=0;i<index;i++) {sum+=buffer[i];} AVERAGE = sum/new Double (index); index=0;//let subscript restore}avghandler.sendemptymessage (1);//Prompt handler update ui}}};/** * Update the display value of the mean * * public void Setaverageview () {//Update textviewif (sumtext==null) return;sumtext.settext (average+ "");} /** * Assigns a value to the average every fixed time and updates the operation of the chart * @autHor Love Fang * */class Avehandler extends handler{@Overridepublic void Handlemessage (Message msg) {//TODO auto-generated Method Stubsetaverageview ();//Display average Updatechart ();//Update chart//put current value in database Dbutils db = Dbutils.create ( Getapplicationcontext ()); Accelerate_info accelerate_info = new Accelerate_info (System.currenttimemillis (), AVERAGE, sensor_id); try {db.save (accelerate_info);//Deposit the current average in database} catch (Dbexception e) {//TODO auto-generated catch Blocke.printstacktrace (); System.out.println ("Save Failed");}}} /** * Accept the measured value of the current sensor, save in the buffer, and add a * @param data */public void Giveaverage (double data) {buffer[index]=data;index++;} /** * Set Chart curve style **/protected xymultipleseriesrenderer buildrenderer (int color, pointstyle style         , Boolean fill) {Xymultipleseriesrenderer renderer = new Xymultipleseriesrenderer ();     Sets the style of the curve itself in the chart, including the color, the size of the point, and the thickness of the line xyseriesrenderer r = new Xyseriesrenderer ();     R.setcolor (color);     R.setpointstyle (style);     R.setfillpoints (fill); R.setlInewidth (2);//This is the line width renderer.addseriesrenderer (r);    return renderer; }/** * Initialize chart * @param renderer * @param xtitle * @param ytitle * @param xMin * @param xmax * @param ymin * @param yMax * @  Param Axescolor * @param labelscolor */protected void setchartsettings (Xymultipleseriesrenderer renderer, String Xtitle, String Ytitle, double xMin, double xmax, double ymin, double yMax, int axescolor, int labelscolor) {//For rendering of the chart see API Documentation Renderer.setcharttitle (Title.gettext (). toString ());//Set Caption Renderer.setxaxismin (xMin);//Set start point of x-axis renderer     . Setxaxismax (Xmax);//Set a screen with how many points renderer.setyaxismin (ymin);     Renderer.setyaxismax (YMax);     Renderer.setbackgroundcolor (Color.Black);     Renderer.setlabelscolor (Color.yellow);     Renderer.setaxescolor (Axescolor);     Renderer.setlabelscolor (Labelscolor);     Renderer.setshowgrid (TRUE); Renderer.setgridcolor (Color.Blue);//Set the color of the lattice renderer.setxlabels (20);//No Eggs with renderer.setylabels (20);// Divide the y-axis scale by the average number of RENderer.setxtitle (xtitle);//x Axis title renderer.setytitle (ytitle);//y Axis title renderer.setylabelsalign (Align.RIGHT);     Renderer.setpointsize ((float) 2);    Renderer.setshowlegend (FALSE);  } int[] XV = new int[1000];//used to display the data double[] YV = new double[1000];  private int addx =-1;  Private double AddY = 0; /** * The function to update the chart is to redraw */private void Updatechart () {//Set the next node to be added AddY = average;//Required        The value to increment//remove the old point set Mdataset.removeseries (series) from the dataset; Determine how many points in the current point set, because the screen can only hold 100, so when the number of points more than 100, the length is always 100//each new point coordinates are moved back one series.add (addx++, AddY);// The most important sentence, in the XY-pair way to put the value if (addx>100) {//If the screen boundary is exceeded, the method of automatic axis movement Renderer.setxaxismin (addX-100);//Display range is     Nderer.setxaxismax (ADDX);          }//Important: Add a new Point set Mdataset.addseries (series) in the data set;    View update, without this step, the curve will not render dynamic//If in non-UI main thread, need to call postinvalidate (), specific reference API Chart.invalidate (); }}



Android uses Achartengine to make dynamic ECG effects

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.