使用处理程序每​​秒更新通知文本

时间:2014-04-22 12:46:00

标签: java android

我有一个奇怪的问题。我想每秒更新通知的文本,所以我写了这段代码

    new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                                batteryTemperature = getBatteryTemperature();

                    new Handler().postDelayed(this, 1000);

                }
            }, 1000);

       if(batteryTemperature != 0) {

builder.setContentText("BatteryLevel"+batteryTemperature);
} else {
builder.setContentText("The batteryTemperature value is 0");
}

使用Log我在Handler中看到,batteryTemperature值与0不同但是在Handler之外它返回0.为什么?如何在通知中设置正确的值?

3 个答案:

答案 0 :(得分:3)

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    batteryTemperature = getBatteryTemperature();
                    handler.postDelayed(this, 1000);
                }
 }, 1000);

每次调用Runnable时都不要创建Handler。每次执行runnable时都需要执行此代码段

  if(batteryTemperature != 0) {
   builder.setContentText("BatteryLevel"+batteryTemperature);
  } else {
    builder.setContentText("The batteryTemperature value is 0");
  }

答案 1 :(得分:1)

试试这个(UI线程安全):

TimerTask task = new TimerTask()
{
    private final Handler   mHandler    = new Handler(Looper.getMainLooper());

    @Override
    public void run()
    {
        mHandler.post(new Runnable()
        {
            @Override
            public void run()
            {
                batteryTemperature = getBatteryTemperature();
                if (batteryTemperature != 0)
                {
                    builder.setContentText("BatteryLevel" + batteryTemperature);
                }
                else
                {
                    builder.setContentText("The batteryTemperature value is 0");
                }
            }
        });
    }
};

Timer timer = new Timer();
timer.scheduleAtFixedRate(task, 0, 1000);

答案 2 :(得分:0)

您要问的有两件事:1)如何更新我的通知; 2)为什么值始终为0?

让我先回答第二个问题,然后尝试使用此代码:

private MyHandler myHandler = new MyHandler();
...
// get the ball rolling...
myHandler.sendEmptyMessageDelayed(MyHandler.UPDATE, 1000);
...
private class MyHandler extends Handler {
    private int UPDATE = 0;

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case UPDATE:
                updateBatteryTemperatureNotification(getBatteryTemperature());
                sendEmptyMessageDelayed(MyHandler.UPDATE, 1000);
                break;
            case STOP:
                removeMessages(UPDATE);
                break;
        }
        super.handleMessage(msg);
    }
}

假设您知道如何在数据正确的情况下更新Notification,这是否安全?