Android device behaves differently when plugged in USB vs not plugged in
I am running tests on an HTC Magic (Dev phone 2). I have 3 background AsyncTasks. One downloads data from a server, one wakes the screen up once a minute and the last keeps the application alive for a given duration. The download thread asynctask seems to work correctly, and while it is downloading(~1hr) the other two seem to work as well. But once the downloads are done if the phone is unplugged the other two threads don't work properly(screen doesn't wake up and the keepAlive never ends). It almost seems like they stop altogether, then if I plug the phone into the computer they start up again... I am not sure what could be causing this, the screen wakeup should be preventing the device from going to sleep.
All my code can be found here: https://homepage.usask.ca/~mcb394/Receive.java or the two classes that seem to stop working after the download completes and when unplugged are below. Any thoughts would be awesome.
/**
* 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);
开发者_如何学C 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;
}
}
The service or activity running this AsyncTask
may be getting killed, which might be affected by being on battery power. Try using a service and using Service.startForeground
.
精彩评论