我正在HTC Magic(Dev phone 2)上運行測試。我有3個背景AsyncTasks。一個從服務器下載數據,一個每分鐘一次喚醒屏幕,最後一個使應用程序在給定的持續時間內保持活動狀態。下載線程asynctask似乎能夠正常工作,並且在下載時(〜1小時),其他兩個似乎也能正常工作。但是,一旦下載完成,如果電話被拔掉,另外兩個線程無法正常工作(屏幕不會喚醒,keepAlive永遠不會結束)。它幾乎看起來像他們完全停止,然後如果我把手機插入電腦,他們再次啓動......我不知道是什麼可能造成這種情況,屏幕喚醒應該是防止設備進入睡眠狀態。Android設備在插入USB或未插入時表現不同
我所有的代碼都可以在這裏找到:https://homepage.usask.ca/~mcb394/Receive.java或者下面兩個類似的東西在下載完成和拔出後似乎停止工作。任何想法都會很棒。
/**
* This class keeps the phone alive for the entire duration necessary to use all the data (think of a media player buffer)
* @author michael bullock
*/
private class KeepRunning extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
try {
Thread.sleep(ALIVE_TIME_MS);
} catch (InterruptedException e) {
out.print(" KeepRunning Crashed!!!!!\n");
out.flush();
e.printStackTrace();
}
out.print(" KeepRunning Completed\n");
out.flush();
timeCompleted = true;
return null;
}
}
/**
* This class powers the phone's screen up every WAKEUP_EVERY ms, stays awake for 1s
* This is so the phone avoids going to sleep
* @author michael bullock
*/
private class WakeUp extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, getClass().getName());
do{
try {
Thread.sleep(WAKEUP_EVERY);
} catch (InterruptedException e) {
e.printStackTrace();
}
wl.acquire();
Log.i("", "********** Acquired Wakelock **********");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("", "********** Releasing Wakelock **********");
wl.release();
}while(!timeCompleted || !transferCompleted);
out.print(" WakeUp Completed\n");
out.flush();
return null;
}
}
更新:我在代碼中放了一些時間戳記的日誌語句,這裏是我發現的......喚醒類應該每分鐘喚醒屏幕直到下載完成。一旦網絡活動停止,它將開始每隔10分鐘而不是1分鐘喚醒屏幕。我將KeepRunning的另一個線程分解爲更小的睡眠,並顯示出類似的結果。非常奇怪。 – Michael 2011-03-04 03:21:59