flutter手机是否锁屏

768 阅读1分钟

在Flutter中,检测手机是否锁屏可以通过DeviceEventPlugin插件来实现,该插件可以监听来自原生平台的事件。但是,Flutter官方插件中并没有直接提供检测锁屏状态的事件,因此你可能需要自定义一个。

以下是一个简单的示例,展示如何检测iOS和Android设备的锁屏状态:

首先,在pubspec.yaml中添加依赖:

dependencies:
  flutter:
    sdk: flutter
  # 添加以下插件用于接收原生事件
  device_event_channel: ^1.0.
  

然后,创建一个自定义的EventChannel来监听锁屏事件:

import 'package:flutter/services.dart';
 
class LockScreenStatus {
  static const EventChannel _eventChannel =
      const EventChannel('lock_screen_event_channel');
 
  static Stream<dynamic> get lockScreenStateChanges {
    return _eventChannel.receiveBroadcastStream();
  }
}

接下来,在原生项目中注册事件和相应的处理逻辑:

iOS

AppDelegate.swift中添加:

import Flutter
import UIKit
 
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  private var lockScreenStreamHandler: FlutterEventChannel?
 
  override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
    lockScreenStreamHandler = FlutterEventChannel(name: "lock_screen_event_channel", binaryMessenger: controller.binaryMessenger)
    lockScreenStreamHandler?.setStreamHandler(self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
 
extension AppDelegate: FlutterStreamHandler {
  public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(forName: UIScreen.didLockNotification, object: nil, queue: .main) { _ in
      events("LOCKED")
    }
    notificationCenter.addObserver(forName: UIScreen.didUnlockNotification, object: nil, queue: .main) { _ in
      events("UNLOCKED")
    }
    
    return nil
  }
 
  public func onCancel(withArguments arguments: Any?) -> FlutterError? {
    let notificationCenter = NotificationCenter.default
    notificationCenter.removeObserver(self, name: UIScreen.didLockNotification, object: nil)
    notificationCenter.removeObserver(self, name: UIScreen.didUnlockNotification, object: nil)
    return nil
  }
}

Android

MainActivity.java中添加:

import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.WindowManager;
 
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.EventChannel;
 
public class MainActivity extends FlutterActivity {
    private EventChannel.StreamHandler streamHandler = new EventChannel.StreamHandler() {
        @Override
        public void onListen(Object o, EventChannel.EventSink eventSink) {
            IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
            filter.addAction(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_USER_PRESENT);
            registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                        eventSink.success("LOCK