android asynctask - Want to run accelerometer in background -


i created app records accelerometer values , stores them in file simple start stop button. want keep working when screen off until stop button pushed best way this. told asynctask not sure if should whole class.

public class startaccelerometer extends activity implements sensoreventlistener,onclicklistener {

private sensormanager sensormanager; private sensor accelerometer; textview title,tvx,tvy,tvz; edittext etshowval; relativelayout layout; private string acc; private string read_str = ""; private final string filepath = "/mnt/sdcard/acc.txt"; private bufferedwriter bufferedwriter; private bufferedreader bufferedreader; private float x; private float y; private float z;  public static final int msg_done = 1; public static final int msg_error = 2; public static final int msg_stop = 3;  private boolean running; private handler handler; private handlerthread handlerthread;   button stop,start;   /** called when activity first created. */ @override public void oncreate(bundle savedinstancestate)  {     super.oncreate(savedinstancestate);     setcontentview(r.layout.activity_accelerometer);     sensormanager = (sensormanager) getsystemservice(context.sensor_service);     accelerometer = sensormanager.getdefaultsensor(sensor.type_accelerometer);     sensormanager.registerlistener(this, accelerometer, android.hardware.sensormanager.sensor_delay_normal);   //get layout     layout = (relativelayout) findviewbyid(r.id.relative);      //get textviews     title = (textview)findviewbyid(r.id.name);        tvx = (textview)findviewbyid(r.id.xval);     tvy = (textview)findviewbyid(r.id.yval);     tvz = (textview)findviewbyid(r.id.zval);     etshowval = (edittext)findviewbyid(r.id.showval);     title.settext("accelerator");      handlerthread = new handlerthread("working thread");     handlerthread.start();      handler = new handler(handlerthread.getlooper());     handler.post(run);      start= (button) findviewbyid(r.id.startaccel);     stop= (button) findviewbyid(r.id.button2);     start.setonclicklistener(this);     stop.setonclicklistener(this); }  private runnable run = new runnable(){     @override     public void run ()     {         while(true)         {             if (running)             {                  try                  {                     writefile(filepath,acc);                                        }                  catch (exception e)                  {                  }              }               try {                 thread.sleep(50);             } catch (interruptedexception e) {                 // todo auto-generated catch block                 e.printstacktrace();             }         }     } };  public void onclick(view view)  {     if(view.getid() == r.id.startaccel){         start();      }     else if(view.getid() == r.id.button2){         stop();     }  }   private synchronized void start() {     running = true; }  private synchronized void stop() {     running = false; }    @override public void onaccuracychanged(sensor sensor, int accuracy)  { }  @override public void onsensorchanged(sensorevent sensorevent)  {     // todo auto-generated method stub      if (sensorevent.sensor.gettype() == sensor.type_accelerometer)      {         x = sensorevent.values[0];          y = sensorevent.values[1];          z = sensorevent.values[2];          acc= string.valueof(x) + ", " + string.valueof(y) + ", " + string.valueof(z);          tvx.settext("x = "+ string.valueof(x));         tvy.settext("y = "+ string.valueof(y));         tvz.settext("z = "+ string.valueof(z));     } }  public void createfile(string path) {     file f = new file(path);     try {         log.d("activity", "create file.");         f.createnewfile();     } catch (ioexception e) {         // todo auto-generated catch block         e.printstacktrace();     } }  public string readfile (string filepath) {     bufferedreader = null;     string tmp = null;      if (!fileisexist(filepath))         createfile(filepath);      try      {         bufferedreader = new bufferedreader(new filereader(filepath));         // read string         while ((tmp = bufferedreader.readline()) != null)          {             tmp += "\n";             read_str += tmp;         }     }      catch (ioexception e)      {         // todo auto-generated catch block         e.printstacktrace();     }     return read_str; }  public void writefile(string filepath, string str) {     bufferedwriter = null;      if (!fileisexist(filepath))         createfile(filepath);      try      {         bufferedwriter = new bufferedwriter(new filewriter(filepath, true));         bufferedwriter.write(str);         bufferedwriter.newline();         bufferedwriter.flush();         bufferedwriter.close();     }     catch (ioexception e)      {         // todo auto-generated catch block         e.printstacktrace();     } }  public boolean fileisexist(string filepath) {     file f = new file(filepath);      if (! f.exists())     {         log.e("activity", "file not exist.");         return false;     }     else         return true; }  @override protected void onpause() { // todo auto-generated method stub    // msensormanager.unregisterlistener(this);    // toast.maketext(this, "unregister accelerometerlistener", toast.length_long).show();     //super.onpause();      super.onpause();     if (running == true) {         sensormanager.unregisterlistener(this); }  

} }

instead of activity use service:

on_start_service --> register listener.

on_stop_service --> unregister listener.

once when u click start_button start service , register sensor , untill click stop_button accelerometer sensor keeps on listening sensor value changes . once if click stop_button unregister listener , last updated value , stop service.

you can manually start , stop service using

startservice() stopservice() 

in onstart() function can add actual functionality carried out.

the service keeps on running in background untill activity terminated.

for more information on services refer http://developer.android.com/guide/components/services.html


Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -