在Android中,我们经常需要使用
Handler
来进行事务的异步处理。其实对于基于主线程的Handler,没有必要到处去创建。另外对于基于非主线程的
Handler
所对应的Thread应该在什么时候退出,始终是一个很难得抉择。因此我封装了一个基于主线程的Handler以便整个程序使用,
并封装了两个基于非主线程
Handler以便整个程序中使用。因为这个
两个基于非主线程
Handler是用于
整个程序中使用的,所以其对应的线程就不退出(直到进程挂掉),自然就少了其
应Thread应该在何时退出的艰难抉择。
源码如下
private
final
static
Handler
mainHandler
=
new
Handler
(
Looper
.
getMainLooper
());
private
final
static
HandlerThread
business0HandlerThread
=
new
HandlerThread
(
"Business0Handler"
);
private
static
Handler
business0Handler
;
private
final
static
HandlerThread
business1HandlerThread
=
new
HandlerThread
(
"Business1Handler"
);
private
static
Handler
business1Handler
;
/*
该Handler运行在主线程中,因此一些必须放在主线程来处理的事务可以用该Hanlder来处理
*/
public
static
Handler
getMainHandler
()
{
return
mainHandler
;
}
/*
该Handler主要用于小事务处理,对于一些耗时但30秒钟能执行完的操作,建议大家放到该Handler来处理
*/
public
static
Handler
getBusiness0Handler
()
{
if
(
business0Handler
==
null
)
{
synchronized
(
AppUtil
.
class
){
if
(
business0Handler
==
null
)
{
business0HandlerThread
.
start
();
business0Handler
=
new
Handler
(
business0HandlerThread
.
getLooper
());
}
}
}
return
business0Handler
;
}
/*
* 该Handler主要用于大事务处理,它可能会非常繁忙,它也许10分钟或许更久都没有空。
*/
public
static
Handler
getBusiness1Handler
()
{
if
(
business1Handler
==
null
)
{
synchronized
(
AppUtil
.
class
){
if
(
business1Handler
==
null
)
{
business1HandlerThread
.
start
();
business1Handler
=
new
Handler
(
business1HandlerThread
.
getLooper
());
}
}
}
return
business1Handler
;
}
使用示例
Runnable
r
=
new
Runnable
()
{
@Override
public
void
run
()
{
// TODO Auto-generated method stub
}
};
getMainHandler
().
post
(
r
);
Runnable
r0
=
new
Runnable
()
{
@Override
public
void
run
()
{
// TODO Auto-generated method stub
}
};
getBusiness0Handler
().
post
(
r0
);
Runnable
r1
=
new
Runnable
()
{
@Override
public
void
run
()
{
// TODO Auto-generated method stub
}
};
getBusiness1Handler
().
post
(
r1
);
使用示例
Runnable
r
=
new
Runnable
()
{
@Override
public
void
run
()
{
// TODO Auto-generated method stub
}
};
getMainHandler
().
post
(
r
);
Runnable
r0
=
new
Runnable
()
{
@Override
public
void
run
()
{
// TODO Auto-generated method stub
}
};
getBusiness0Handler
().
post
(
r0
);
Runnable
r1
=
new
Runnable
()
{
@Override
public
void
run
()
{
// TODO Auto-generated method stub
}
};
getBusiness1Handler
().
post
(
r1
);
标签:Runnable,封装,void,Handler,static,new,一点,public
From: https://blog.51cto.com/u_15170706/6320239