插入USB与未插入时,Android设备的行为有所不同

时间:2011-03-03 23:37:45

标签: android multithreading background sleep

我正在对HTC Magic(开发手机2)进行测试。我有3个背景AsyncTasks。一个从服务器下载数据,一个每分钟唤醒一次屏幕,最后一个使应用程序保持活动一段时间。下载线程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;
    }
}

1 个答案:

答案 0 :(得分:1)

运行此AsyncTask的服务或活动可能会被杀死,这可能会受到电池供电的影响。尝试使用服务并使用Service.startForeground