当我收到SOS时,如果我在一段时间内点击按钮,我希望能够取消短信发送。
时间在GUI上配置,应为int delay = Integer.parseInt(cancelTime.getText().toString())*1000;
,例如10x1000 = 10秒,点击按钮。
if(data.equals("SOS\r\n")) {
startTime = System.currentTimeMillis();
Handler handler = new Handler();
int delay = Integer.parseInt(cancelTime.getText().toString())*1000;
handler.postDelayed(new Runnable() {
@Override
public void run() {
double elapsedTime = ((System.currentTimeMillis() - startTime)/1000);
alertButton.setText("CANCEL THE SOS: " + elapsedTime);
alertButton.setBackgroundColor(Color.parseColor("#FF0000"));
alertButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
wasCanceled = true;
}
});
if(!wasCanceled)
{
//SEND SMS
}
else if(wasCanceled)
{
alertButton.setText("CANCELED!!");
alertButton.setTextColor(Color.parseColor("#008000"));
}
}
}, delay);
}
}
我的问题是GUI没有更新。它仅在我单击按钮时更新。
alertButton.setText("CANCEL THE SOS: " + elapsedTime);
alertButton.setBackgroundColor(Color.parseColor("#FF0000"));
此外,我希望时间减少到10 ... 9 ......直到0. Atm正在递增。
答案 0 :(得分:0)
尝试这样的事情:
if ("SOS\r\n".equals(data))
{
final long startTime = System.currentTimeMillis();
final Handler handler = new Handler();
final int delay = Integer.parseInt(cancelTime.getText()) * 1000;
final long endTime = startTime + delay;
wasCanceled = false;
alertButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
wasCanceled = true;
}
});
final Runnable r = new Runnable()
{
@Override
public void run()
{
final double remainingTime = (endTime - System.currentTimeMillis()) / 1000d;
alertButton.setText("CANCEL THE SOS: " + elapsedTime);
alertButton.setBackgroundColor(Color.parseColor("#FF0000"));
if(wasCanceled)
{
alertButton.setText("CANCELED!!");
alertButton.setTextColor(Color.parseColor("#008000"));
return;
}
else if(remainingTime < 0)
{
// SEND SMS
return;
}
handler.postDelayed(r, 1000);
}
};
handler.postDelayed(r, 1000);
}
由于在完成某些操作后它会自行重新postDelayed()
,您可能希望将内部延迟从1000
降低到800
或类似的东西......