简体   繁体   中英

BroadCast receiver invoking if screen is off

我正在做一个应用程序,如果我们摇动手机锁定屏幕,我已经写了关闭屏幕的代码,但现在问题是我需要一个广播接收器,检查屏幕是否关闭,我该怎么办?

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM