我正在尝试使用带有TimerTask()和postDelayed相关联的Handler()来每隔1秒更新一次我运行方法任务的通知,但是从事物的外观来看,我似乎正在碰壁正确地实现它。
这是我的代码示例:

 Timer timer = new Timer();
    TimerTask task = new TimerTask(){

            @Override
            public void run() {
                updateNotificationUi();
            }
        };

        timer.scheduleAtFixedRate(task, 0, 1000);
}


然后updateNotificationUi()方法代码:

private void updateNotificationUi() {

    new Handler().postDelayed(new Runnable(){

        @Override
        public void run() {

            if(isRunning) {

  mNotificationBuilder.setContentTitle("Text").setContentText("This value here updates every 1 sec").setSmallIcon(R.drawable.ic_launcher);

 mNotifyManager.notify(notificationID, mNotificationBuilder.build());


            }
        }

    }, 1000);
}


运行我的应用程序时出现的错误是12-22 07:37:20.556: E/AndroidRuntime(6555): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
有关如何解决此问题的任何建议?

最佳答案

是的,还有一个更优雅的解决方案

您可以将Handler和Runnable定义为这样的全局变量(注意runnable内部的“ postDelayed”):

Handler myHandler;

Runnable runnable = new Runnable(){

    @Override
    public void run() {

        if(isRunning) {

           mNotificationBuilder.setContentTitle("Text").setContentText("This value here updates every 1 sec").setSmallIcon(R.drawable.ic_launcher);

           mNotifyManager.notify(notificationID, mNotificationBuilder.build());

           myHandler.postDelayed(runnable, 1000);
        }
    }

};

...


然后在您的方法中开始循环:

private void updateNotificationUi() {

    myHandler = new Handler();

    myHandler.postDelayed(runnable, 1000);
}


可能您也将需要一个停止条件,也许在runnable内部有一个布尔标志arroung“ postDelayed”。像这样:

if(shouldContinueLooping){
    myHandler.postDelayed(runnable, 1000);
}

10-07 22:42