package com.example.testthreadhandler;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView threadTextView;
Button threadBtn;
int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
threadTextView = (TextView) findViewById(R.id.threadTextView);
threadBtn = (Button) findViewById(R.id.threadBtn);
Log.i("TAG", "mainThread : " + Thread.currentThread().getId());
threadBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
new mThread().start();
}
});
}
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
threadTextView.setText(i + "");
break;
case 2:
threadTextView.setText("are you kidding me ?");
break;
}
};
};
class mThread extends Thread {
@Override
public void run() {
super.run();
Log.i("TAG", "Thread : " + Thread.currentThread().getId());
while (i < 10) {
i++;
Message msg = new Message();
msg.what = 1;
mHandler.sendMessage(msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Message msg = new Message();
msg.what = 2;
mHandler.sendMessage(msg);
}
}
}
子线程+Handler简单实现
最新推荐文章于 2024-02-23 17:39:43 发布