1、HandlerThread 用法实例
package com.example.handledemos;
import com.example.handledemos.util.LogUtil;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* 主线程与子线程之间的信息交互
* @author lzl
*用到HandlerThread方法,主要解决多线程并发问题。
*/
public class HandlerThreadActivity extends Activity implements OnClickListener{
//创建主线程中的handler
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
Message message = new Message();
//handlerthread每隔1秒向子线程发送一次消息。
handlerthread.sendMessageDelayed(message, 1000);
LogUtil.i("主线程", "Main send the message");
};
};
private Handler handlerthread;
private HandlerThread thread;
private Button button1;
private Button button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.handlerthread);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
thread = new HandlerThread("threadHandler");
thread.start();
handlerthread = new Handler(thread.getLooper()){
@Override
public void handleMessage(Message msg) {
Message message = new Message();
//handler每隔1秒向主线程发送一次消息。
handler.sendMessageDelayed(message, 1000);
LogUtil.i("子线程", "Thread send the message");
}
};
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
handler.sendEmptyMessage(1);
break;
case R.id.button2:
handler.removeMessages(0); //传入0时会停止发送消息。
break;
default:
break;
}
}
}
2、Log控制打印,在完成大型项目后,运行程序是还会打印Log信息,程序员不可能将其逐个删除掉。因此可以写个Util包,来控制Log日志的打印。
当完成工程后,就不用担心这个问题了。
package com.example.handledemos.util;
import android.util.Log;
public class LogUtil {
public static final int VERBOSE = 1;
public static final int DEBUG = 2;
public static final int INFO = 3;
public static final int WARN = 4;
public static final int ERROR = 5;
public static final int NOTHING = 6;
public static final int LEVEL = NOTHING;
public static void v(String tag , String msg){
if(LEVEL <= VERBOSE){
Log.v(tag, msg);
}
}
public static void d(String tag , String msg){
if(LEVEL <= DEBUG){
Log.d(tag, msg);
}
}
public static void i(String tag , String msg){
if(LEVEL <= INFO){
Log.i(tag, msg);
}
}
public static void w(String tag , String msg){
if(LEVEL <= WARN){
Log.w(tag, msg);
}
}
public static void e(String tag , String msg){
if(LEVEL <= ERROR){
Log.e(tag, msg);
}
}
}