// Version 1
public class IAmAThread extends Thread {
public IAmAThread() {
super("IAmAThread");
}
@Override
public void run() {
// your code (sequence of instructions)
}
}
// to execute this sequence of instructions in a separate thread.
new IAmAThread().start();
// Version 2
public class IAmARunnable implements Runnable {
@Override
public void run() {
// your code (sequence of instructions)
}
}
// to execute this sequence of instructions in a separate thread.
IAmARunnable myRunnable = new IAmARunnable();
new Thread(myRunnable).start();
> A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread/message queue of the thread that is creating it — from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
public class TestActivity extends Activity {
// ...
// all standard stuff
@Override
public void onCreate(Bundle savedInstanceState) {
// ...
// all standard stuff
// we're creating a new handler here
// and we're in the UI Thread (default)
// so this Handler is associated with the UI thread
Handler mHandler = new Handler();
// I want to start doing something really long
// which means I should run the fella in another thread.
// I do that by sending a message - in the form of another runnable object
// But first, I'm going to create a Runnable object or a message for this
Runnable mRunnableOnSeparateThread = new Runnable() {
@Override
public void run () {
// do some long operation
longOperation();
// After mRunnableOnSeparateThread is done with it's job,
// I need to tell the user that i'm done
// which means I need to send a message back to the UI thread
// who do we know that's associated with the UI thread?
mHandler.post(new Runnable(){
@Override
public void run(){
// do some UI related thing
// like update a progress bar or TextView
// ....
}
});
}
};
// Cool but I've not executed the mRunnableOnSeparateThread yet
// I've only defined the message to be sent
// When I execute it though, I want it to be in a different thread
// that was the whole point.
new Thread(mRunnableOnSeparateThread).start();
}
}
// the below code is inside a TextWatcher
// which implements the onTextChanged method
// I've simplified it to only highlight the parts we're
// interested in
private long lastChange = 0;
@Override
public void onTextChanged(final CharSequence chars,
int start, int before, int count) {
// The handler is spawned from the UI thread
new Handler().postDelayed(
// argument 1 for postDelated = message to be sent
new Runnable() {
@Override
public void run() {
if (noChangeInText_InTheLastFewSeconds()) {
searchAndPopulateListView(chars.toString());
// logic
}
}
},
// argument 2 for postDelated = delay before execution
300);
lastChange = System.currentTimeMillis();
}
private boolean noChangeInText_InTheLastFewSeconds() {
return System.currentTimeMillis() - lastChange >= 300
}
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare(); //创建本线程的Looper并创建一个MessageQueue
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop(); //开始运行Looper,监听Message Queue
}
}
public class ListProgressDemo extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listprogress);
((Button) findViewById(R.id.load_Handler)).setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
data = null;
data = new ArrayList<string>();
adapter = null;
showDialog(PROGRESS_DIALOG);
new ProgressThread(handler, data).start();
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
switch(id) {
case PROGRESS_DIALOG:
return ProgressDialog.show(this, "",
"Loading. Please wait...", true);
default: return null;
}
}
private class ProgressThread extends Thread {
private Handler handler;
private ArrayList<string> data;
public ProgressThread(Handler handler, ArrayList<string> data) {
this.handler = handler;
this.data = data;
}
@Override
public void run() {
for (int i=0; i<8; i++) {
data.add("ListItem"); //后台数据处理
try {
Thread.sleep(100);
}catch(InterruptedException e) {
Message msg = handler.obtainMessage();
Bundle b = new Bundle();
b.putInt("state", STATE_ERROR);
msg.setData(b);
handler.sendMessage(msg);
}
}
Message msg = handler.obtainMessage();
Bundle b = new Bundle();
b.putInt("state", STATE_FINISH);
msg.setData(b);
handler.sendMessage(msg);
}
}
// 此处甚至可以不需要设置Looper,因为Handler默认就使用当前线程的Looper
private final Handler handler = new Handler(Looper.getMainLooper()) {
public void handleMessage(Message msg) { // 处理Message,更新ListView
int state = msg.getData().getInt("state");
switch(state){
case STATE_FINISH:
dismissDialog(PROGRESS_DIALOG);
Toast.makeText(getApplicationContext(),
"加载完成!",
Toast.LENGTH_LONG)
.show();
adapter = new ArrayAdapter<string>(getApplicationContext(),
android.R.layout.simple_list_item_1,
data );
setListAdapter(adapter);
break;
case STATE_ERROR:
dismissDialog(PROGRESS_DIALOG);
Toast.makeText(getApplicationContext(),
"处理过程发生错误!",
Toast.LENGTH_LONG)
.show();
adapter = new ArrayAdapter<string>(getApplicationContext(),
android.R.layout.simple_list_item_1,
data );
setListAdapter(adapter);
break;
default:
}
}
};
private ArrayAdapter<string> adapter;
private ArrayList<string> data;
private static final int PROGRESS_DIALOG = 1;
private static final int STATE_FINISH = 1;
private static final int STATE_ERROR = -1;
}
((Button) findViewById(R.id.load_AsyncTask)).setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
data = null;
data = new ArrayList<string>();
adapter = null;
//显示ProgressDialog放到AsyncTask.onPreExecute()里
//showDialog(PROGRESS_DIALOG);
new ProgressTask().execute(data);
}
});
private class ProgressTask extends AsyncTask, Void, Integer> {
/* 该方法将在执行实际的后台操作前被UI thread调用。可以在该方法中做一些准备工作,如在界面上显示一个进度条。*/
@Override
protected void onPreExecute() {
// 先显示ProgressDialog
showDialog(PROGRESS_DIALOG);
}
/* 执行那些很耗时的后台计算工作。可以调用publishProgress方法来更新实时的任务进度。 */
@Override
protected Integer doInBackground(ArrayList<string>... datas) {
ArrayList<string> data = datas[0];
for (int i=0; i<8; i++) {
data.add("ListItem");
}
return STATE_FINISH;
}
/* 在doInBackground 执行完成后,onPostExecute 方法将被UI thread调用,
* 后台的计算结果将通过该方法传递到UI thread.
*/
@Override
protected void onPostExecute(Integer result) {
int state = result.intValue();
switch(state){
case STATE_FINISH:
dismissDialog(PROGRESS_DIALOG);
Toast.makeText(getApplicationContext(),
"加载完成!",
Toast.LENGTH_LONG)
.show();
adapter = new ArrayAdapter<string>(getApplicationContext(),
android.R.layout.simple_list_item_1,
data );
setListAdapter(adapter);
break;
case STATE_ERROR:
dismissDialog(PROGRESS_DIALOG);
Toast.makeText(getApplicationContext(),
"处理过程发生错误!",
Toast.LENGTH_LONG)
.show();
adapter = new ArrayAdapter<string>(getApplicationContext(),
android.R.layout.simple_list_item_1,
data );
setListAdapter(adapter);
break;
default:
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有