Handler message transmission mechanism (4) The subthread receives messages sent by the main thread, and the handler thread
Package com. example. logoff; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. logoff; import android. OS. message; import android. view. view; import android. view. view. onClickListener; import android. widget. button; public class MainActivity extends Activity {private Button send; private Handler handler; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); send = (Button) findViewById (R. id. button1); new Thread (new MyThread ()). start (); // The main thread has a default Loopersend. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {Message message = Message. obtain (); message. obj = "Jackson"; handler. sendMessage (message) ;}});} public class MyThread implements Runnable {@ Overridepublic void run () {// logoff is not defined in the subthread. prepare (); // cyclic Message Queue // handler = new Handler () {@ Override public void handleMessage (Message msg) is instantiated in the subthread) {// receives the message super from the main thread in the Child thread. handleMessage (msg); System. out. println ("-- get a message from the main thread -->" + msg. obj) ;}}; Looper. loop ();}}}
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" android: paddingBottom = "@ dimen/activity_vertical_margin" android: paddingLeft = "@ dimen/plugin" android: paddingRight = "@ dimen/plugin" android: paddingTop = "@ dimen/plugin" tools: context = "com. example. logoff. mainActivity "> <Button android: id =" @ + id/button1 "android: layout_width =" fill_parent "android: layout_height =" wrap_content "android: layout_alignParentTop =" true "android: layout_centerHorizontal = "true" android: layout_marginTop = "56dp" android: text = "Send message"/> </RelativeLayout>
View output results under Logcat
Source code download