screen_lock_plugin 0.0.2
screen_lock_plugin: ^0.0.2 copied to clipboard
A Flutter plugin that allows you to lock the Android device screen programmatically using Device Admin permissions.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:screen_lock_plugin/screen_lock_plugin.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _screenLockPlugin = ScreenLockPlugin();
bool _isAdminEnabled = false;
bool? _isScreenOn;
String _lastScreenEvent = 'None';
StreamSubscription<String>? _screenEventSub;
@override
void initState() {
super.initState();
_checkAdminStatus();
_subscribeToScreenEvents();
_checkScreenState();
}
Future<void> _checkAdminStatus() async {
final isEnabled = await _screenLockPlugin.isDeviceAdminEnabled();
setState(() {
_isAdminEnabled = isEnabled ?? false;
});
}
Future<void> _checkScreenState() async {
final isOn = await _screenLockPlugin.isScreenOn();
setState(() {
_isScreenOn = isOn;
});
}
void _subscribeToScreenEvents() {
_screenEventSub = _screenLockPlugin.onScreenStateChanged().listen((event) {
setState(() {
_lastScreenEvent = event;
});
});
}
Future<void> _requestAdmin() async {
await _screenLockPlugin.requestDeviceAdmin();
await _checkAdminStatus();
}
Future<void> _lockScreen() async {
final result = await _screenLockPlugin.lockScreen();
if (!result!) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Device admin not enabled. Please enable it first.'),
),
);
}
}
}
@override
void dispose() {
_screenEventSub?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Screen Lock Plugin Example')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Device Admin Status: ${_isAdminEnabled ? "Enabled" : "Disabled"}',
style: const TextStyle(fontSize: 18),
),
const SizedBox(height: 20),
Text(
'Screen is currently: ${_isScreenOn == null ? "..." : (_isScreenOn! ? "ON" : "OFF")}',
style: const TextStyle(fontSize: 18),
),
const SizedBox(height: 12),
Text(
'Last screen event: $_lastScreenEvent',
style: const TextStyle(fontSize: 16),
),
const SizedBox(height: 24),
ElevatedButton(
onPressed: _isAdminEnabled ? null : _requestAdmin,
child: const Text('Enable Device Admin'),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _isAdminEnabled ? _lockScreen : null,
child: const Text('Lock Screen'),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _checkScreenState,
child: const Text('Check Screen State'),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _checkAdminStatus,
child: const Text('Refresh Status'),
),
],
),
),
),
);
}
}