emvaized
emvaized

Reputation: 1135

Flutter app - ability to turn off the screen

Is there any way to lock the screen from Flutter app on Android? I'm talking about the same action that happens when the user presses the phone's power button.

Upvotes: 5

Views: 5582

Answers (2)

Iheb Briki
Iheb Briki

Reputation: 276

Hello maybe my answer is late but I made a plugin that performs exactly the implementation mentioned in the comment below with some other functions

device_policy_manager

and this how u can use it

/// Return `true` if the given administrator component is currently active (enabled) in the system.
final status = await DevicePolicyManager.isPermissionGranted();

/// request administrator permission
/// it will open the adminstartor permission page and return `true` once the permission granted.
/// An optional message providing additional explanation for why the admin is being added.
await DevicePolicyManager.requestPermession("Your app is requesting the Adminstration permission");

/// Remove administration permission from the current app.
await DevicePolicyManager.removeActiveAdmin();

/// Make the device lock immediately, as if the lock screen timeout has expired at the point of this call.
/// After this method is called, the device must be unlocked using strong authentication (PIN, pattern, or password).
await DevicePolicyManager.lockNow();

/// Determine whether or not the device's cameras have been disabled for this user.
final status = await DevicePolicyManager.isCameraDisabled();

Upvotes: 3

Jitesh Mohite
Jitesh Mohite

Reputation: 34250

This is not available on flutter till now, for it we have to take the help of native implementation. Follow the below implementation.

Flutter Code:

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static const platform = const MethodChannel('flutter.native/powerOff');

  Future<void> responseFromNativeCode() async {
    try {
      await platform.invokeMethod('powerOff');
    } on PlatformException catch (e) {
      print("Failed to Invoke: '${e.message}'.");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Center(
        child: RaisedButton(
          child: Text('Turn Off'),
          onPressed: responseFromNativeCode,
        ),
      ),
    );
  }
}

Java Code:

1. MainActivity

    import io.flutter.embedding.android.FlutterActivity;
    import io.flutter.embedding.engine.FlutterEngine;
    import io.flutter.plugin.common.MethodCall;
    import io.flutter.plugin.common.MethodChannel;
    import android.content.Context;
    import android.app.Activity;
    import android.app.admin.DevicePolicyManager;
    import android.content.ComponentName;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.widget.Toast;

    public class MainActivity extends FlutterActivity {
        private static final String CHANNEL = "flutter.native/powerOff";
        static final int RESULT_ENABLE = 1;
        DevicePolicyManager deviceManger;
        ComponentName compName;

    @Override
    public void configureFlutterEngine(FlutterEngine flutterEngine) {
        compName = new ComponentName(this, DeviceAdmin.class);
        deviceManger = (DevicePolicyManager)
                getSystemService(Context.DEVICE_POLICY_SERVICE);
        super.configureFlutterEngine(flutterEngine);
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL).setMethodCallHandler(
                new MethodChannel.MethodCallHandler() {
                    @Override
                    public void onMethodCall(MethodCall call, MethodChannel.Result result) {
                        if (call.method.equals("powerOff")) {
                            Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
                            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, compName);
                            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "You should enable the app!");
                            startActivityForResult(intent, RESULT_ENABLE);
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_ENABLE:
                if (resultCode == Activity.RESULT_OK) {
                    deviceManger.lockNow();
                }
                return;
        }
    }
}

2. Receiver Code

import android.app.admin.DeviceAdminReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class DeviceAdmin extends DeviceAdminReceiver {
    @Override
    public void onEnabled(Context context, Intent intent) {
        super.onEnabled(context, intent);
        Toast.makeText(context, "Enabled", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDisabled(Context context, Intent intent) {
        super.onDisabled(context, intent);
        Toast.makeText(context, "Disabled", Toast.LENGTH_SHORT).show();
    }
}

3. AndroidMenifest.xml

 <receiver
        android:name=".DeviceAdmin"
        android:description="@string/app_description"
        android:label="@string/app_name"
        android:permission="android.permission.BIND_DEVICE_ADMIN">
        <meta-data
            android:name="android.app.device_admin"
            android:resource="@xml/policies" />
        <intent-filter>
            <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
        </intent-filter>
    </receiver>

4.policies.xml - Add in res/xml folder

<?xml version="1.0" encoding="utf-8"?>
<device-admin>
    <uses-policies>
        <force-lock />
    </uses-policies>
</device-admin>

and Finally, add String value in strings.xml file of the android project which required in the receiver

Upvotes: 5

Related Questions