How to keep screen on when an android app is running in the background?

1.2k views Asked by At

I have a requirement for my android app to keep the screen on at all times whenever the app is running (either in the foreground or in the background).

My initial attempt was to was FLAG_KEEP_SCREEN_ON from WindowManager.Layout params in my main activity's onCreate method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

However, this only seemed to work when the activity was currently running the foreground. Any execution of onPause (closing UI or navigating to a new activity) would eventually cause the screen to switch off.

After reviewing https://developer.android.com/training/scheduling/wakelock and other threads related to keeping the application running in the background (e.g. How to make an android app run in background when the screen sleeps?), the latest approach is to use PowerManager.FULL_WAKE_LOCK from a service started when the MainActivity is launched. Code below:

MainActivity:

package com.example;

import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Keep screen on when app is running in background
        Intent i = new Intent(getApplicationContext(), ScreenOnService.class);
        startService(i);
    }
}

ScreenOnService:

package com.example;

import android.app.Service;
import android.content.Intent;
import android.os.PowerManager;

public class ScreenOnService extends Service {

    private int NOTIFICATION = 1;
    private PowerManager.WakeLock wakeLock;

    @Override
    public void onCreate() {
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "KeepScreenOn");
        wakeLock.acquire();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        wakeLock.release();
        super.onDestroy();
    }
}

Now once the service is started, the screen will not switch off when I navigate to other activities. However, if I close the UI the screen will still eventually switch off, even though I can see the service is still running. How can I prevent the screen from switching off even when the app runs in the background?

0

There are 0 answers