和大家一起探讨Android线程已经有些日子了,谈的最多的就是如何把子线程中的数据发送给主线程进行处理,进行UI界面的更新,为什么要这样,请查阅之前的随笔。本篇我们就来讨论一下关于主线程向子线程如何发送数据,这个用的地方也是非常的多,例如当我们为了优化用户体验,我们会在不影响用户使用的情况下进行后台数据更新,好了废话不多说,开始我们今天的讨论。
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);//每隔1S向子线程发送一个Message对象 }; }; //子线程中的Handler private Handler SecondHandler; @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);//每隔1S向主线程发送一个Message对象 } }; } 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; } } }
布局文件:
<?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>