我想在我的Android App中实现多个计时器,每个计时器独立于另一个计时器,并且来自App生命周期。
使用这些运行计时器,我想:
我的问题是如何更好地实现多线程? 如何设法与正在运行的线程进行通信?
我想创建一些非常接近原生Android计时器应用的东西。
以下是我每次添加一个计时器时创建新线程的方法(但是一旦启动计时器我无法与线程通信)
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
try {
showCountDownTimer(enteredTimeFormatted);
showNotification(nameOfFood, id_food);
timer.start();
} catch (Exception e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
stopSelf(msg.arg1);
}
}
private void showCountDownTimer(long number) {
timer = new CountDownTimer(number, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timeLeft = millisUntilFinished;
normalTime = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(timeLeft),
TimeUnit.MILLISECONDS.toMinutes(timeLeft) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeLeft)),
TimeUnit.MILLISECONDS.toSeconds(timeLeft) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeLeft)));
Log.i(LOG_TAG, "time left = " + normalTime);
counter = millisUntilFinished / 1000;
updateNotification(nameOfFood, id_food);
Intent timerInfoIntent = new Intent(TIME_INFO);
timerInfoIntent.putExtra("VALUE", normalTime);
LocalBroadcastManager.getInstance(NotificationService.this).sendBroadcast(timerInfoIntent);
}
@Override
public void onFinish() {
counter = 0;
readyNotification(nameOfFood, id_food);
Intent timerInfoIntent = new Intent(TIME_INFO);
timerInfoIntent.putExtra("VALUE", "Dish is ready!");
LocalBroadcastManager.getInstance(NotificationService.this).sendBroadcast(timerInfoIntent);
}
};
}
答案 0 :(得分:0)
使用loopers和handlers。您可能会发现此文章有用:https://developer.android.com/training/multiple-threads/create-threadpool.html