Hanlder SendMessage 发送标志位,发送字符串。
这里简单说下SendMessage 与 obtainMessage() 的区别:
SendMessage 每次都要New一个新的对象,相对obtainMessage()虽然体会不到快慢,但是确实多占用内存,所以推荐使用Handler.obtainMessage()
package com.suchuanhong.study;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class MainActivity extends Activity {
private Thread thread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyThread mythread=new MyThread();
thread=new Thread(mythread);
thread.start();
}
public static Handler connHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
int arg1 = msg.arg1;
String string1 = msg.getData().getString("time");
Log.i("sunzn", String.valueOf(arg1));
Log.i("sunzn", string1);
}
};
class MyThread implements Runnable
{
@Override
public void run() {
while(true)
{
try {
Thread.sleep(1000);
Message message=connHandler.obtainMessage();
Bundle bundle=new Bundle();
bundle.putString("time", "senOK");
message.setData(bundle);
connHandler.sendMessage(message);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
这里简单说下SendMessage 与 obtainMessage() 的区别:
SendMessage 每次都要New一个新的对象,相对obtainMessage()虽然体会不到快慢,但是确实多占用内存,所以推荐使用Handler.obtainMessage()
package com.suchuanhong.study;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class MainActivity extends Activity {
private Thread thread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyThread mythread=new MyThread();
thread=new Thread(mythread);
thread.start();
}
public static Handler connHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
int arg1 = msg.arg1;
String string1 = msg.getData().getString("time");
Log.i("sunzn", String.valueOf(arg1));
Log.i("sunzn", string1);
}
};
class MyThread implements Runnable
{
@Override
public void run() {
while(true)
{
try {
Thread.sleep(1000);
Message message=connHandler.obtainMessage();
Bundle bundle=new Bundle();
bundle.putString("time", "senOK");
message.setData(bundle);
connHandler.sendMessage(message);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}