Search code examples
androidcpuandroid-powermanager

How to keep CPU running while closing screen?


There is a time-consuming task (a Thread) in Fragment. It works fine. But, when I close the screen, I see the CPU not work so that the task cannot work fine.

I have use PowerManager in Activity, but not work Fragment too. Also add <uses-permission android:name="android.permission.WAKE_LOCK" />

@Override
protected void onResume() {
    super.onResume();
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "CPUKeepRunning");
    wakeLock.acquire();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (wakeLock != null && wakeLock.isHeld()) {
        wakeLock.release();
        wakeLock = null;
    }
}

I have saw the CPU enter image description here


Solution

  • Run your code through a Service, if you're running it in an Activity it will stop once the activity goes in the background. Use Services instead.

    http://developer.android.com/training/run-background-service/create-service.html http://developer.android.com/guide/components/services.html