寫這篇文章的目的,是看到羣裏有人在實現延遲的時候,用以下的第四種方法,我的感受有點不妥,爲了防止更多的人有這種想法,因此本身抽空深刻分析,就分析的結果,寫下此文,但願對部分人有啓示做用。java
答: 1.java.util.Timer類的:android
public void schedule(TimerTask task, long delay) {
if (delay < 0)
throw new IllegalArgumentException("Negative delay.");
sched(task, System.currentTimeMillis()+delay, 0);
}
複製代碼
2.android.os.Handler類:bash
public final boolean postDelayed(Runnable r, long delayMillis)
{
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
複製代碼
3.android.app.AlarmManager類:app
@SystemApi
@RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS)
public void set(@AlarmType int type, long triggerAtMillis, long windowMillis,
long intervalMillis, OnAlarmListener listener, Handler targetHandler,
WorkSource workSource) {
setImpl(type, triggerAtMillis, windowMillis, intervalMillis, 0, null, listener, null,
targetHandler, workSource, null);
}
複製代碼
4.Thread.sleep()而後在必定時間以後再執行想執行的代碼:async
new Thread(new Runnable(){
Thead.sleep(4*1000);
doTask();
}).start()
複製代碼
5.View.postDelay:ide
public boolean postDelayed(Runnable action, long delayMillis) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.postDelayed(action, delayMillis);
}
// Postpone the runnable until we know on which thread it needs to run.
// Assume that the runnable will be successfully placed after attach.
getRunQueue().postDelayed(action, delayMillis);
return true;
}//這個原理和2是相似的,暫不作分析了
複製代碼
答:oop
private void mainLoop() {
while (true) {
try {
TimerTask task;
boolean taskFired;
synchronized(queue) {
// Wait for queue to become non-empty
while (queue.isEmpty() && newTasksMayBeScheduled)
queue.wait();
if (queue.isEmpty())
break; // Queue is empty and will forever remain; die
// Queue nonempty; look at first evt and do the right thing
long currentTime, executionTime;
task = queue.getMin();
synchronized(task.lock) {
if (task.state == TimerTask.CANCELLED) {
queue.removeMin();
continue; // No action required, poll queue again
}
currentTime = System.currentTimeMillis();
executionTime = task.nextExecutionTime;
if (taskFired = (executionTime<=currentTime)) {
if (task.period == 0) { // Non-repeating, remove
queue.removeMin();
task.state = TimerTask.EXECUTED;
} else { // Repeating task, reschedule
queue.rescheduleMin(
task.period<0 ? currentTime - task.period
: executionTime + task.period);
}
}
}
if (!taskFired) // Task hasn't yet fired; wait queue.wait(executionTime - currentTime); } if (taskFired) // Task fired; run it, holding no locks task.run(); } catch(InterruptedException e) { } } } 複製代碼
是經過wait和延遲時間到達的時候,調用notify來喚起線程繼續執行,這樣來實現延遲的話,咱們能夠會開啓一個新的線程,貌似爲了個延遲不必這樣吧,等到須要定時,頻繁執行的任務,再考慮這個吧。post
Message next() {
......
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
......
}
}
複製代碼
當咱們向MessageQueue插入一條延遲的Message的時候,Looper在執行loop方法,底層會調用epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);其中的timeoutMillis參數指定了在沒有事件發生的時候epoll_wait調用阻塞的毫秒數(milliseconds)。這樣咱們在以前的時間內這個時候阻塞了是會釋放cpu的資源,等到延遲的時間到了時候,再監控到事件發生。在這裏可能有人會有疑問,一直阻塞,那我接下來的消息應該怎麼執行呢?咱們能夠看到當咱們插入消息的時候的方法:測試
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
複製代碼
阻塞了有兩種方式喚醒,一種是超時了,一種是被主動喚醒了,在上面咱們能夠看到當有消息進入的時候,咱們會喚醒繼續執行,因此咱們的即時消息在延遲消息以後插入是沒有關係的。而後在延遲時間到了的時候,咱們也會被喚醒,執行對應的消息send,以達到延遲時間執行某個任務的目的。 優點:這種延遲在阻塞的時候,是會釋放cpu的鎖,不會過多地佔用cpu的資源。
ui
IAlarmManager mService.set(mPackageName, type, triggerAtMillis, windowMillis, intervalMillis, flags,
operation, recipientWrapper, listenerTag, workSource, alarmClock);
複製代碼
這裏是經過aidl與AlarmManagerService的所在進程進行通訊,具體的實現是在AlarmManagerService類裏面:
private final IBinder mService = new IAlarmManager.Stub() {
@Override
public void set(String callingPackage,
int type, long triggerAtTime, long windowLength, long interval, int flags,
PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
final int callingUid = Binder.getCallingUid();
if (interval != 0) {
if (directReceiver != null) {
throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
}
}
if (workSource != null) {
getContext().enforcePermission(
android.Manifest.permission.UPDATE_DEVICE_STATS,
Binder.getCallingPid(), callingUid, "AlarmManager.set");
}
flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
| AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED); DeviceIdleController.
if (callingUid != Process.SYSTEM_UID) {
flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
}
if (windowLength == AlarmManager.WINDOW_EXACT) {
flags |= AlarmManager.FLAG_STANDALONE;
}
if (alarmClock != null) {
flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
} else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
|| Arrays.binarySearch(mDeviceIdleUserWhitelist,
UserHandle.getAppId(callingUid)) >= 0)) {
flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
}
setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
}
}
}
複製代碼
雖然有人以爲用AlarmManager可以在應用關閉的狀況下,定時器還能再喚起,通過本身的測試,當殺掉應用程序的進程,AlarmManager的receiver也是接收不到消息的,可是我相信在這裏定時器確定是發送了,可是做爲接收方的應用程序進程被殺掉了,執行不了對應的代碼。不過有人也以爲AlarmManager更耗電,是由於咱們執行定時任務的狀況會頻繁喚起cpu,可是若是隻是用來只是執行延遲任務的話,我的以爲和Handler.postDelayed()相比應該也不會耗電多的。
如上面咱們看到的這樣,若是是單純的實現一個任務的延遲的話,咱們能夠用Handler.postDelayed()和AlarmManager.set()來實現,用(4)的方法Thread.sleep()的話,首先開啓一個新的線程,而後會持有cpu的資源,用(1)的方法,Timer,會開啓一個死循環的線程,這樣在資源上面都有點浪費。
若是你們還有更好的延遲解決方案,能夠拿出來你們探討,要是文章有不對的地方,歡迎拍磚。
若是大家以爲文章對你有啓示做用,但願大家幫忙點個贊或者關注下,謝謝