0
我想在我的Android應用中實現多個定時器,每個定時器獨立於另一個應用生命週期。帶定時器的多線程
有了這些正在運行的定時器,我想:
- 顯示所有的人都在一個專門的活動
- 對於每個定時器,使用戶能夠刪除它,加入1分鐘的可能性,暫停
- 讓他們運行和發送聲音通知時,定時器達到零時,即使用戶已經關閉了應用程序
- 使用的廣播接收機,我更新的剩餘秒每個第二狀態
我的問題是如何更好地實現多個線程? 如何管理與正在運行的線程進行通信?
我想創建一些非常接近原生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);
}
};
}
請問我可以給我一些教程或例子嗎?我試圖只是閱讀文檔來實現它,但沒有成功 – Alex
也許你可以試着在遷移到實現線程池之前先注入一個looper。本文可能對您有所幫助:http://stackoverflow.com/questions/7597742/what-is-the-purpose-of-looper-and-how-to-use-it – jdesesquelles