我正在 HTC Magic(开发手机 2)上运行测试。我有 3 个背景 AsyncTasks。一个从服务器下载数据,一个每分钟唤醒一次屏幕,最后一个让应用程序在给定的时间内保持 Activity 状态。下载线程 asynctask 似乎可以正常工作,并且在下载时(~1 小时)其他两个似乎也可以正常工作。但是一旦下载完成,如果拔下电话,其他两个线程将无法正常工作(屏幕不会唤醒并且 keepAlive 永远不会结束)。看起来它们似乎完全停止了,然后如果我将手机插入计算机,它们会再次启动……我不确定是什么原因造成的,屏幕唤醒应该会阻止设备进入休眠状态。
我的所有代码都可以在这里找到: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;
}
}
最佳答案
运行此 AsyncTask
的服务或 Activity 可能会被终止,这可能会受到电池供电的影响。尝试使用服务并使用 Service.startForeground
。
关于Android 设备插入 USB 与未插入时的行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5188005/