Geethu
Geethu

Reputation: 1616

BroadCast receiver invoking if screen is off

I am doing an app which lock the screen if we shake the phone, I had written the code for screen off,But now the problem is I need a broadcast receiver which checks whether the screen is off or on, how can I do it?

Upvotes: 1

Views: 1728

Answers (2)

MichaelP
MichaelP

Reputation: 2781

If you need to check whether the screen off or on at a particular moment, here is a good way for you, no need to register a receiver

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
boolean isScreenOn = powerManager.isScreenOn();
if (!isScreenOn) {//lock screen
   //do something
}

In case you want to listen whenever the screen goes off, then you need register a receiver. For Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON you CANNOT declare them in your Android Manifest, but they must be registered in an IntentFilter in your JAVA code,and don't need to add any permission

public class ScreenReceiver extends BroadcastReceiver {

    public static boolean wasScreenOn = true;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            // do whatever you need to do here
            wasScreenOn = false;
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            // and do whatever you need to do here
            wasScreenOn = true;
        }
    }

}

Then register receiver in onCreate of your activity

  @Override
    protected void onCreate() {
       //your code
        BroadcastReceiver mReceiver = new ScreenReceiver();
        registerReceiver(mReceiver, filter);            
    }

And unregister in onDestroy of your activity

 @Override
    protected void onDestroy() {
       //your code
        unregisterReceiver(mReceiver);         

    }

Hope this help you.

Upvotes: 3

Dixit Patel
Dixit Patel

Reputation: 3192

hope this Link

Which help to u better way to implement BroadCastReciever invoking if screen is off in Android.

EDIT:

You have to Add permission into manifest just like:

<receiver android:name=".MyBroadCastReciever">
    <intent-filter>
        <action android:name="android.intent.action.SCREEN_OFF"/>
        <action android:name="android.intent.action.SCREEN_ON"/>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

Upvotes: 0

Related Questions