android - Implementing Runnable in MainActivity -
i have activity prints custom date time string textview. implemented runnable interface in mainactivity self , created thread
@ end of oncreate
method.
thread thread = new thread(this); thread.run();
this run method
public void run() { while (true) { try { thread.sleep(1000); localtime.settext(localtime.gettime().format2445()); system.out.println(localtime.gettime().format2445()); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } } }
when run on emulator can see system out in logcat. emulator shows anr after 5 seconds. doing wrong. method not suitable? async task way go here? need update clock every second having asynctask run forever acceptable pattern?
you need start thread.start()
http://developer.android.com/reference/java/lang/thread.html
quoting docs
there 2 ways execute code in new thread. can either subclass thread , overriding run() method, or construct new thread , pass runnable constructor. in either case, start() method must called execute new thread..
you calling thread.run()
. calling sleep . should not block ui thread.
http://developer.android.com/training/articles/perf-anr.html
if looking count down timer
http://developer.android.com/reference/android/os/countdowntimer.html
countdowntimer in minutes , seconds.
you can use handler, timer task. if use timer task make sure udate ui on ui thread.
edit: failed notice this. above comments. credits doctordrive
localtime.settext(localtime.gettime().format2445()); // update ui thread not possible
you need use runonuithread
runonuithread(new runnable() //run on ui thread { public void run() { localtime.settext(localtime.gettime().format2445()); } });
Comments
Post a Comment