有些需求要不停的执行handler,但是由于handler是挂载在looper线程副本中,looper在启动loop方法后不断地执行MessageQueue中的消息,会不断地调用handleMessage,所以当activity结束后并不能结束handler的运行,这时候我们需要对Looper进行操作,handler.getLooper().quit();结束Looper循环,以下是代码
public class MainActivity extends Activity
{
int i = 0;
private Handler handler;
private Looper looper;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.start);
button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
start();
}
});
HandlerThread ht = new HandlerThread("myThread")//这里比较关键
{
@Override
public void run()
{
Looper.prepare();
looper = Looper.myLooper();
looper.loop();
Log.d("TAG", looper.toString());
}
};
ht.start();
}
public void start()
{
handler = new Handler(looper)
{
public void handleMessage(Message msg)
{
if (msg.what == 0)
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.sendEmptyMessage(0);
}
};
};
handler.sendEmptyMessage(0);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (KeyEvent.KEYCODE_BACK == keyCode)
{
finish();
handler.getLooper().quit();
}
return false;
}
}