AsyncTask 4.0 以后默认串行,为了避免并行错误。在3.0以上可以通过executeOnExecutor();
HandlerThread
HandlerThread 继承Thread, 内部实现:run()方法中通过Looper.prepare()创建队列,通过Looper.loop()开启消息循环,这样就允许在HandlerThread 中创建Handler了。
new Handler(mHandlerThread.getLooper); Handler的传入Looper创建方法。
//示例代码:
private void initBackThread()
{
mCheckMsgThread = new HandlerThread("check-message-coming");
mCheckMsgThread.start();
mCheckMsgHandler = new Handler(mCheckMsgThread.getLooper())
{
@Override
public void handleMessage(Message msg)
{
//请求网络等耗时操作
checkForUpdate();
if (isUpdateInfo)
{
//间隔1s重复调用HandlerThread
mCheckMsgHandler.sendEmptyMessageDelayed(MSG_UPDATE_INFO, 1000);
}
}
};
}
private void checkForUpdate()
{
try
{
//模拟耗时
Thread.sleep(1000);
mHandler.post(new Runnable()
{
@Override
public void run()
{
String result = "实时更新中,当前大盘指数:<font color='red'>%d</font>";
result = String.format(result, (int) (Math.random() * 3000 + 1000));
mTvServiceInfo.setText(Html.fromHtml(result));
}
});
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
IntentService
内部维护了一个HandlerThread 和Handler 。onStartCommand()的时候会mServiceHandler.sendMessage(msg)添加到messageQueue中,说明没调用一次就会添加一次。
private final class ServiceHandler extends Handler{
public ServiceHandler(Looper looper){
super(looper);
}
@Override
public void handleMessage(Message msg){
onHandleIntent((Intent)msg.obj); // 需要用户自行复写处理逻辑
stopSelf(msg.arg1); // 可以说明IntentService当任务处理完成后会自动销毁
}
}
public class LocalIntentService extends IntentService{
private static final String TAG="LOCALINTENTSERVICE";
public LocalIntentSercie(){
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent){
//任务逻辑
SystemClock.sleep(3000);
}
@Override
public void onDestory(){
super.onDestory();
}
}