随便写两句
android编程使用消息, 网上经常看到这样的例子.
timer = new Timer();
final Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
...
}
};
timer.scheduleAtFixedRate(new TimerTask()
{
@Override
public void run()
{
Message mesasge = new Message();
mesasge.what = 1;
handler.sendMessage(mesasge);
}
}, 0, 10);
上面的例子中实际上存在着内存泄露,正确的写法应该是这样:
timer.scheduleAtFixedRate(new TimerTask()
{
@Override
public void run()
{
Message message = handler.obtainMessage(); //handler is an instance of type Handler
//Set fields of message
message.what = 1;
message.sendToTarget();
}
}, 0, 10);
timer = new Timer();
final Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
...
}
};
timer.scheduleAtFixedRate(new TimerTask()
{
@Override
public void run()
{
Message mesasge = new Message();
mesasge.what = 1;
handler.sendMessage(mesasge);
}
}, 0, 10);
上面的例子中实际上存在着内存泄露,正确的写法应该是这样:
timer.scheduleAtFixedRate(new TimerTask()
{
@Override
public void run()
{
Message message = handler.obtainMessage(); //handler is an instance of type Handler
//Set fields of message
message.what = 1;
message.sendToTarget();
}
}, 0, 10);