The main thread of the Android thread sends messages to the subthread, and android sends messages.
I have been discussing with you about Android threads for some days. The most talked about is how to send data from sub-threads to the main thread for processing and UI updates. Why, please refer to the previous documents. In this article, we will discuss how the main thread sends data to the sub-thread, which is also widely used. For example, when we want to optimize the user experience, we will update the background data without affecting the user's usage. Well, we will discuss it today.
Public class ThreadActivity extends Activity implements OnClickListener {private Button button1; private Button button2; // Handler private Handler firstHandler = new Handler () {public void handleMessage (android. OS. message msg) {System. out. println ("first:" + Thread. currentThread (); Message message = new Message (); SecondHandler. sendMessageDelayed (message, 1000); // sends a Message object to the subthread every 1 s;}; // Handler private Handler SecondHandler in the subthread; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. four); init (); into ();} private void into () {HandlerThread handlerThread = new HandlerThread ("handler Thread"); handlerThread. start (); SecondHandler = new Handler (handlerThread. getLooper () {@ Override public void handleMessage (Message msg) {System. out. println ("Second:" + Thread. currentThread (); Message message = new Message (); firstHandler. sendMessageDelayed (message, 1000); // sends a Message object to the main thread every 1 s;} private void init () {button1 = (Button) findViewById (R. id. button1); button2 = (Button) findViewById (R. id. button2); button1.setOnClickListener (this); button2.setOnClickListener (this) ;}@ Override public void onClick (View arg0) {switch (arg0.getId () {case R. id. button1: firstHandler. sendEmptyMessage (1); break; case R. id. button2: firstHandler. removeMessages (1); break; default: break ;}}}
Layout file:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="send" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="stop" /></LinearLayout>