Android的Handler使用
如何每隔一段时间进行一些操作呢,Handler就可以做到。 下面的Demo的功能为每隔3秒显示MyItems数组中的不同数据。
public
class
MainActivity
extends
Activity {
private
int
count =
0
;
private
static
final
String[] MyItems = {
"Here is a Item1"
,
"Here is a Item2"
,
"Here is a Item3"
,
"Here is a Item4"
};
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Timer timer =
new
Timer();
timer.scheduleAtFixedRate(
new
Newtask(),
10
,
3000
);
}
private
Handler hand =
new
Handler(){
public
void
handleMessage(Message msg){
switch
(msg.what)
{
case
1
:
Toast.makeText(MainActivity.
this
, MyItems[count], Toast.LENGTH_SHORT).show();
if
(count ==
3
)
count =
0
;
else
count++;
break
;
}
};
};
private
class
Newtask
extends
TimerTask
{
@Override
public
void
run() {
// TODO Auto-generated method stub
Message msg =
new
Message();
msg.what =
1
;
hand.sendMessage(msg);
}
}
}
|
下面的文章讲解的比较详细:
本文转自Work Hard Work Smart博客园博客,原文链接:http://www.cnblogs.com/linlf03/archive/2013/03/14/2958909.html,如需转载请自行联系原作者