Android|循环线程和Handler消息执行

一、线程循环启动,直到满足条件
1、定义Handler
【Android|循环线程和Handler消息执行】class MainHandler extends Handler
{
public MainHandler(){}


public MainHandler(Looper L)
{
super(L);
}


public void handleMessage(MessagenMsg)
{
switch(nMsg.what)
{
case 0:
Log.i(TAG,"nMsg.what =0");
stockbroadcast(); //发送STOCK
break;
}
}
}


2、OnCreate中启动线程


Looper lop = Looper.myLooper();
mMainHandler=new MainHandler(lop);
runnable=new Runnable(){
@Override
public void run() {
if(isDataReady())//满足条件
{//发送股票的广播
stockbroadcast(); //发送股票的广播
}
else
{//重新执行
Log.i(TAG,"postDelayed");
mMainHandler.postDelayed(this, 100); //延时100ms
}
}
};
mMainHandler.postDelayed(runnable, 100);

二、Handler发送msg执行操作
1、定义Handler
class MainHandler extends Handler
{
public MainHandler(){}


public MainHandler(Looper L)
{
super(L);
}


public void handleMessage(MessagenMsg)
{
switch(nMsg.what)
{
case 0:
Log.i(TAG,"nMsg.what =0");
stockbroadcast(); //发送STOCK
break;
}


2、OnCreate中定义对象
MainHandlermMainHandler; //定义Handler对象
3、发送消息:
mMainHandler.sendEmptyMessage(0);

    推荐阅读