1

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

Pang
  • 9,564
  • 146
  • 81
  • 122
zys
  • 1,306
  • 3
  • 18
  • 37
  • avoid to use long-running operations in fragments or activity. try to replace your thread to service, and acquire wakeLock before start operation and release wright after end your long-running operation – ant Nov 28 '15 at 01:47
  • why service not thread ? – zys Nov 28 '15 at 01:54
  • you can use thread inside service. Service creates to perform long-running operations and minimize wide range of troubles that may occurs with using long running threads in activity or fragment. You can read a lot about services here http://developer.android.com/guide/components/services.html – ant Nov 28 '15 at 02:08

1 Answers1

1

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

Lakhshya Bansal
  • 293
  • 1
  • 2
  • 13
  • I use `WakefulBroadcastReceiver` and `IntentService` .It works fine! [http://developer.android.com/intl/zh-cn/training/scheduling/wakelock.html](http://developer.android.com/intl/zh-cn/training/scheduling/wakelock.html) – zys Nov 29 '15 at 14:22