package com.example.handlerdemowjj;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
// 另外的线程
private static final int MSG_SUCCESS = 0;// 获取成功的标识
private static final int MSG_FAILURE = 1;// 获取失败的标识
private Thread mThread;
TextView tv;
private Handler mHandler = new Handler(){
public void handleMessage(Message msg) {// 此方法在ui线程运行
switch (msg.what) {
case MSG_SUCCESS:
Log.v("logcat", "MSG_SUCCESS" + Thread.currentThread());
Log.v("logcat", "MSG_SUCCESS_ID:"
+ Thread.currentThread().getId() + ",name="
+ Thread.currentThread().getName());
Toast.makeText(getApplication(), "成功", Toast.LENGTH_LONG)
.show();
tv.setText("new.成功");
break;
case MSG_FAILURE:
Log.v("logcat", "MSG_FAILURE" + Thread.currentThread());
Toast.makeText(getApplication(), "失败", Toast.LENGTH_LONG)
.show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
Runnable runnable = new Runnable() {
@Override
public void run() {
//这是新的线程,可在这儿处理耗时的操作,更新不了UI界面的操作的
Log.v("logcat",
"new-Thread.currentThread()=" + Thread.currentThread());
Log.v("logcat", "new-Thread.currentThread().getId()="
+ Thread.currentThread().getId() + ",name="
+ Thread.currentThread().getName());
int i = 0;
if (i == 0) {
mHandler.obtainMessage(MSG_SUCCESS).sendToTarget();// 获取成功
} else {
mHandler.obtainMessage(MSG_FAILURE).sendToTarget();// 获取失败
}
}
};
if (mThread == null) {
Toast.makeText(getBaseContext(), "mThread == null",
Toast.LENGTH_LONG).show();
mThread = new Thread(runnable);
mThread.start();// 线程启动
} else {
Toast.makeText(getBaseContext(), "thread_started",
Toast.LENGTH_LONG).show();
}
}
}