android - sendMessage() is not defined -
i trying create example know how handlers work. shown in code belwo, created workerthread runs ever , increment variable i. within run() method, want pass value of incremented variable textview shown in body of handler class.
the problem is, line in there "new handler()" , "handler.sendmessage(m)" marked red
please let me know how solve problem
mainactivity
public class mainactivity extends appcompatactivity { private final static string tag = mainactivity.class.getclass().getsimplename(); private textview mtvincr = null; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); this.mtvincr = (textview) findviewbyid(r.id.tvvalue); new workerthread().start(); } handler handler =new handler() {//error @override public void handlemessage(message msg) { int sentint = msg.getdata().getint("what"); mtvincr.settext("r:"+integer.tostring(sentint)); } }; class workerthread extends thread { private int = 0; android.os.handler mhandler = null; @override public void run() { super.run(); looper.prepare(); while(true) { log.d(tag, subtag.bullet("workerthread", "i: " + (i++))); systemclock.sleep(1000); message m = new message(); bundle b = new bundle(); b.putint("what", i); // example m.setdata(b); handler.sendmessage(m);//error } } } }
use message.obtain()
message object
while constructor of message public, best way 1 of these call message.obtain() or 1 of handler.obtainmessage() methods, pull them pool of recycled objects.
and use obj
attribute msg.obj = b;
obj: arbitrary object send recipient.
info from:
https://developer.android.com/reference/android/os/message.html
example:
handler handler =new handler() { @override public void handlemessage(message msg) { int sentint = ((bundle)msg.obj).getint("what"); mtvincr.settext("r:"+integer.tostring(sentint)); } }; class workerthread extends thread { private int = 0; android.os.handler mhandler = null; @override public void run() { super.run(); looper.prepare(); while(true) { log.d(tag, subtag.bullet("workerthread", "i: " + (i++))); systemclock.sleep(1000); message msg = message.obtain(); bundle b = new bundle(); b.putint("what", i); // example msg.obj = b; handler.sendmessage(msg); } } }
Comments
Post a Comment