Skip to content Skip to sidebar Skip to footer

How To Stop A Background Thread When The Screen In Android Device Goes Off

I have a background thread in my app. Now when the screen goes off(after say 15 seconds), the thread is running and hence does not behave as I prefer. So, in which method of the Ac

Solution 1:

Do you want it to run when the app is in the background (if the user is in another app)? If not, onPause. If so, then you'd need a BroadcastReceiver to capture the screen turning off, and stop it in respect to that.

IntentFilter screenStateFilter = new IntentFilter();
screenStateFilter.addAction(Intent.ACTION_SCREEN_ON);
screenStateFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenStateReceiver, screenStateFilter);

Java file :

onReceive(Intent i) {
   if( i.getAction().equals(Intent.ACTION_SCREEN_ON) ) {
        // turn your thread start if you want or anything else
   } else if( i.getAction().equals(Intent.ACTION_SCREEN_OFF) ) {
        // turn your thread cancel here
   }
}

And just in case you don't know, a warning- do not use thread.stop() to stop it. It can cause crashes, memory/resource leaks, and deadlocks. Cancel the thread instead and have the thread poll to see if its canceled.


Post a Comment for "How To Stop A Background Thread When The Screen In Android Device Goes Off"