Reputation: 61
Is there a way to turn on android screen when received push notification from FCM or somewhere else?
I want it will turn on even if the app is in background, and even if the app is killed.
In addition, I want that the notification will make sound even if the device is in silent mode. Is it possible?
edit
I called this function in onMessageReceived(), after a few minutes of the screen being off, its not work, its not turns it back:
private fun wakeApp() {
val pm = applicationContext.getSystemService(POWER_SERVICE) as PowerManager
val screenIsOn = pm.isInteractive // check if screen is on
if (!screenIsOn) {
val wakeLockTag = packageName + "WAKELOCK"
val wakeLock = pm.newWakeLock(
PowerManager.FULL_WAKE_LOCK or
PowerManager.ACQUIRE_CAUSES_WAKEUP or
PowerManager.ON_AFTER_RELEASE, wakeLockTag
)
//acquire will turn on the display
wakeLock.acquire()
//release will release the lock from CPU, in case of that, screen will go back to sleep mode in defined time bt device settings
wakeLock.release()
}
}
Upvotes: 2
Views: 542
Reputation: 75
It's simple, just call this function in your onMessagesReceived method. I also use this in my project.
private fun wakeApp() {
val pm = applicationContext.getSystemService(POWER_SERVICE) as PowerManager
val screenIsOn = pm.isInteractive // check if screen is on
if (!screenIsOn) {
val wakeLockTag = packageName + "WAKELOCK"
val wakeLock = pm.newWakeLock(
PowerManager.FULL_WAKE_LOCK or
PowerManager.ACQUIRE_CAUSES_WAKEUP or
PowerManager.ON_AFTER_RELEASE, wakeLockTag
)
//acquire will turn on the display
wakeLock.acquire()
//release will release the lock from CPU, in case of that, screen will go back to sleep mode in defined time bt device settings
wakeLock.release()
}
}
Also don't forget to add this permission in manifest:
<uses-permission android:name="android.permission.WAKE_LOCK" />
And for making sound even in silent mode you can use the below code which will actually set the volume dynamically when notification is received and play the sound through MediaPlayer:
AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, 0);
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(this, R.raw.example);
mediaPlayer.setVolume(1.0f, 1.0f);
mediaPlayer.start();
Upvotes: 0