multithreading - How can I run code on a background thread on Android? -
i want code run in background continuously. don't want in service. there other way possible?
i have tried calling thread
class in activity
activity
remains in background sometime , stops. thread
class stops working.
class testthread implements runnable { @override public void run() { file file = new file(environment.getexternalstoragedirectory(),"/bpcltracker/gpsdata.txt"); int i=0; randomaccessfile in = null; try { in = new randomaccessfile(file, "rw"); } catch (filenotfoundexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } //string line =null; while (true) { httpentity entity=null; try { if (isinterneton()) { while ((line = in.readline()) != null) { httpclient client = new defaulthttpclient(); string url = "some url"; httppost request = new httppost(url); stringentity se = new stringentity(line); se.setcontentencoding("utf-8"); se.setcontentencoding(new basicheader(http.content_type, "application/json")); entity = se; request.setentity(entity); httpresponse response = client.execute(request); entity = response.getentity(); i++; } if((line = in.readline()) == null && entity!=null) { file.delete(); testthread t = new testthread(); thread t1 = new thread(t); t1.start(); } }// end of if else { thread.sleep(60000); } // end of else }// end of try catch (nullpointerexception e1) { e1.printstacktrace(); } catch (interruptedexception e2) { e2.printstacktrace(); } catch (ioexception e1) { // todo auto-generated catch block e1.printstacktrace(); } }// end of while }// end of run
if need to:
execute code on background thread
execute code not touch/update ui
execute (short) code take @ few seconds complete
then use following clean , efficient pattern uses asynctask:
asynctask.execute(new runnable() { @override public void run() { //todo background code } });
Comments
Post a Comment