Detecting Screen on and Screen Off via services

Hi buddies, have a happy Sunday.

Today I'll explore about detecting screen on and screen off in android devices.

I got your mind, can use also by Broad cast Receivers. Yes, you can.

But how do you know, if app goes offline and screen off.

First write the Broad cast receiver class for receiving results.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class ScreenReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            screenOff = true;
            Log.i("screenLog", "screen off");

        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            screenOff = false;
            Log.i("screenLog", "screen on");

Then write the service class:


import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.appl.ex.receiver.ScreenReceiver;

public class UpdateScreen extends Service {
    BroadcastReceiver mReceiver;

    public void onCreate() {
        // register receiver that handles screen on and screen off logic
        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        mReceiver = new ScreenReceiver();
        registerReceiver(mReceiver, filter);

    public void onDestroy() {
        Log.i("onDestroy Reciever", "Called");

    public void onStart(Intent intent, int startId) {
        boolean screenOn = intent.getBooleanExtra("screen_state", false);
        if (!screenOn) {
            Log.i("screenON", "Called");
            Toast.makeText(getApplicationContext(), "Awake", Toast.LENGTH_LONG)
        } else {
            Log.i("screenOFF", "Called");
            Toast.makeText(getApplicationContext(), "Sleep",

    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;

    public int onStartCommand(Intent intent, int flags, int startId) {
        return Service.START_STICKY;
Add the permission in Manifest, like this.

<uses-permission android:name="android.permission.DEVICE_POWER" />

Inside the Application:

<service android:name=".service.UpdateScreen" />

Finally start the service in your activity:

Intent service = new Intent(DrawerActivity.this, UpdateScreen.class);


Popular posts from this blog

Clear the app data programmatically in android

convert an integer to a string in java

Print the large string values in android log cat.