我已經從這個鏈接學習WakefulBroadcastReceiver:https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html混淆WakefulBroadcastReceiver
我有這方面的困惑幾個:
- 這是否接收器可以確保在設備是你甚至接收廣播在睡眠模式下? (我認爲不是,只是在收到廣播後才讓設備保持清醒狀態,直到致電完成WakefulIntent()爲止。)
- 該文檔說明了在接收方內使用意圖服務,並且在完成工作之後,完成WakefulIntent。
CODE:
import android.app.IntentService;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;
public class SimpleWakefulService extends IntentService {
public SimpleWakefulService() {
super("SimpleWakefulService");
}
@Override
protected void onHandleIntent(Intent intent) {
// At this point SimpleWakefulReceiver is still holding a wake lock
// for us. We can do whatever we need to here and then tell it that
// it can release the wakelock. This sample just does some slow work,
// but more complicated implementations could take their own wake
// lock here before releasing the receiver's.
//
// Note that when using this approach you should be aware that if your
// service gets killed and restarted while in the middle of such work
// (so the Intent gets re-delivered to perform the work again), it will
// at that point no longer be holding a wake lock since we are depending
// on SimpleWakefulReceiver to that for us. If this is a concern, you can
// acquire a separate wake lock here.
for (int i=0; i<5; i++) {
Log.i("SimpleWakefulReceiver", "Running service " + (i+1)
+ "/5 @ " + SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
SimpleWakefulReceiver.completeWakefulIntent(intent);
}
}
現在,作爲文檔說,這個接收方持有喚醒鎖,我高度懷疑,這是一個很好的做法,開始像從接收器的意圖的服務。這會阻止接收器釋放喚醒鎖並耗盡大量電池,因爲服務通常用於長操作。
即使上面的代碼片斷突出顯示,在釋放鎖之前有25秒的延遲。這是使用該接收機的正確方式,還是隻能用於短時間操作?任何幫助表示讚賞。
我不是一個完美的人說它的好或壞的做法,但它的作品完美 –
基本上沒有對reciver本身的引用......它只是開始持有的意圖鎖...和* *靜態**方法釋放鎖... – Selvin
@Selvin即使沒有參考(我的意思是靜態方法,正如你所建議的),仍然存在喚醒鎖,這將會消耗電池嗎? –