当我开始学习 android 时,我编写了这个示例代码来处理线程中的消息,方法是looper
:
public class MainActivity extends Activity {
Handler mHandler,childHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new Handler(){
public void handleMessage(Message msg) {
TextView tv = (TextView) findViewById(R.id.displayMessage);
tv.setText(msg.obj.toString());
}
};
new LooperThread().start();
}
public void onSend(View v){
Message msg = childHandler.obtainMessage();
TextView tv = (TextView) findViewById(R.id.messageText);
msg.obj = tv.getText().toString();
childHandler.sendMessage(msg);
}
@Override
protected void onStart() {
super.onStart();
LooperThread ttTest = new LooperThread();
ttTest.start();
}
class LooperThread extends Thread {
final int MESSAGE_SEND = 1;
public void run() {
Looper.prepare();
childHandler = new Handler() {
public void handleMessage(Message msg) {
Message childMsg = mHandler.obtainMessage();
childMsg.obj = "child is sending "+(String)msg.obj;
mHandler.sendMessage(childMsg);
}
};
Looper.loop();
}
}
}
它是一个示例代码,用于在按下按钮时向线程发送消息,然后线程通过向主活动添加一些字符串再次发送消息。您可以根据需要操作此代码。
Activity默认有looper,所以不需要为activity编写looper。
线程默认没有looper,所以我们需要写looper,它是一种存储消息的队列。
更新:
XML 代码
<LinearLayout 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:orientation="vertical" >
<EditText
android:id="@+id/messageText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Input message">
<requestFocus />
</EditText>
<TextView
android:id="@+id/displayMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</TextView>
<Button
android:id="@+id/buttonSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onSend"
android:text="Send" />
</LinearLayout>