要实现在 Android 屏幕关闭前收到广播的功能,可以使用以下步骤:
public class ScreenOffReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
// 在屏幕关闭前执行的操作
Log.d("ScreenOffReceiver", "Screen is about to turn off");
}
}
}
ScreenOffReceiver screenOffReceiver = new ScreenOffReceiver();
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(screenOffReceiver, intentFilter);
这样,当屏幕关闭前,你将收到一个名为 "android.intent.action.SCREEN_OFF" 的广播,并且可以在 ScreenOffReceiver 类的 onReceive() 方法中执行你想要的操作。