0

我正在尝试在服务中运行 Timer onStartCommand(,它实际上会获取一些数据并向用户显示定期更新/刷新的数据。

现在,我希望用户能够控制周期/刷新时间。我的想法是运行两个计时器:一个将向用户显示更新的数据,另一个将检查用户是否更改了刷新时间/周期,如果用户更改了,它将取消其他时间并再次运行随着新时期。

这是我的任务的主要代码:

     final Messenger mMessenger = new Messenger(new IncomingHandler()); 

@Override
public IBinder onBind(Intent intent) {
    return mMessenger.getBinder();
}

static class IncomingHandler extends Handler { // Handler of incoming
                                                   // messages from
    // clients.
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case MSG_SET_REFRESH_TIME:
            String refreshTemp = msg.getData().getString("refresh");
            refreshTime = Long.parseLong(refreshTemp);
            isNewRefresh = true;
            break;
        default:
            super.handleMessage(msg);
        }
    }
}

    public synchronized int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("MyService", "Received start id " + startId + ": " + intent);
    showNotification();

    timerRefresh.schedule(new TimerTask() {
        public void run() {
            checkRefreshTimeUpdate();
            // onTimerTick();
        }
    }, 0, 1000);
    isRunning = true;

    timer.schedule(new TimerTask() {
        public void run() {
            UpdateNeighbor();
        }
    }, 0, refreshTime);
    isRunning = true;

    return START_STICKY; 
}

    private void checkRefreshTimeUpdate() {
    Log.d("Refresh Updater: ", "Updater run'ing");

    if (isNewRefresh) {
        timer.cancel();

        timer.schedule(new TimerTask() {
            public void run() {
                UpdateNeighbor();
                // onTimerTick();
            }
        }, 0, refreshTime);
        isRunning = true;
        isNewRefresh = false;
    }
}

现在,每当我运行我的服务并在其运行时,我按下按钮输入我的新 preiod/刷新时间,程序崩溃并在 logcat 中显示如下:

07-18 17:30:08.738: E/AndroidRuntime(6954): FATAL EXCEPTION: Timer-1
07-18 17:30:08.738: E/AndroidRuntime(6954): java.lang.IllegalStateException: Timer was canceled
07-18 17:30:08.738: E/AndroidRuntime(6954):     at java.util.Timer.scheduleImpl(Timer.java:561)
07-18 17:30:08.738: E/AndroidRuntime(6954):     at java.util.Timer.schedule(Timer.java:481)
07-18 17:30:08.738: E/AndroidRuntime(6954):     at com.exampleservice.MyService.checkRefreshTimeUpdate(MyService.java:269)
07-18 17:30:08.738: E/AndroidRuntime(6954):     at com.exampleservice.MyService.access$7(MyService.java:263)
07-18 17:30:08.738: E/AndroidRuntime(6954):     at com.exampleservice.MyService$1.run(MyService.java:210)
07-18 17:30:08.738: E/AndroidRuntime(6954):     at java.util.Timer$TimerImpl.run(Timer.java:284)

如果有人可以在这里帮助我,甚至可以找到更好的方法来实现我的目标,我将不胜感激:)

4

0 回答 0