Skip to content

[camera][android] takePicture not completed after pausePreview #113532

Description

@SofiSheromova

Hi! I found a bug on my android device. If you call _cameraController.takePicture() before calling _cameraController.pausePreview(), then the takePicture function will not complete.

Device: Redmi Note 8 Pro, Android 11

Expected results: the snapshot was saved successfully

Actual results: the function takePicture is not completed.

Code sample

The example is taken from https://docs.flutter.dev/cookbook/plugins/picture-using-camera and supplemented with a line await _controller.pausePreview(); before final image = await _controller.takePicture();

import 'dart:async';
import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';

Future<void> main() async {
  // Ensure that plugin services are initialized so that `availableCameras()`
  // can be called before `runApp()`
  WidgetsFlutterBinding.ensureInitialized();

  // Obtain a list of the available cameras on the device.
  final cameras = await availableCameras();

  // Get a specific camera from the list of available cameras.
  final firstCamera = cameras.first;

  runApp(
    MaterialApp(
      theme: ThemeData.dark(),
      home: TakePictureScreen(
        // Pass the appropriate camera to the TakePictureScreen widget.
        camera: firstCamera,
      ),
    ),
  );
}

// A screen that allows users to take a picture using a given camera.
class TakePictureScreen extends StatefulWidget {
  const TakePictureScreen({
    super.key,
    required this.camera,
  });

  final CameraDescription camera;

  @override
  TakePictureScreenState createState() => TakePictureScreenState();
}

class TakePictureScreenState extends State<TakePictureScreen> {
  late CameraController _controller;
  late Future<void> _initializeControllerFuture;

  @override
  void initState() {
    super.initState();
    // To display the current output from the Camera,
    // create a CameraController.
    _controller = CameraController(
      // Get a specific camera from the list of available cameras.
      widget.camera,
      // Define the resolution to use.
      ResolutionPreset.medium,
    );

    // Next, initialize the controller. This returns a Future.
    _initializeControllerFuture = _controller.initialize();
  }

  @override
  void dispose() {
    // Dispose of the controller when the widget is disposed.
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Take a picture')),
      // You must wait until the controller is initialized before displaying the
      // camera preview. Use a FutureBuilder to display a loading spinner until the
      // controller has finished initializing.
      body: FutureBuilder<void>(
        future: _initializeControllerFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            // If the Future is complete, display the preview.
            return CameraPreview(_controller);
          } else {
            // Otherwise, display a loading indicator.
            return const Center(child: CircularProgressIndicator());
          }
        },
      ),
      floatingActionButton: FloatingActionButton(
        // Provide an onPressed callback.
        onPressed: () async {
          // Take the Picture in a try / catch block. If anything goes wrong,
          // catch the error.
          try {
            // Ensure that the camera is initialized.
            await _initializeControllerFuture;

            // Attempt to take a picture and get the file `image`
            // where it was saved.
            await _controller.pausePreview();
            final image = await _controller.takePicture();

            if (!mounted) return;

            // If the picture was taken, display it on a new screen.
            await Navigator.of(context).push(
              MaterialPageRoute(
                builder: (context) => DisplayPictureScreen(
                  // Pass the automatically generated path to
                  // the DisplayPictureScreen widget.
                  imagePath: image.path,
                ),
              ),
            );
          } catch (e) {
            // If an error occurs, log the error to the console.
            print(e);
          }
        },
        child: const Icon(Icons.camera_alt),
      ),
    );
  }
}

// A widget that displays the picture taken by the user.
class DisplayPictureScreen extends StatelessWidget {
  final String imagePath;

  const DisplayPictureScreen({super.key, required this.imagePath});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Display the Picture')),
      // The image is stored as a file on the device. Use the `Image.file`
      // constructor with the given path to display the image.
      body: Image.file(File(imagePath)),
    );
  }
}
Logs
[        ] An Observatory debugger and profiler on Redmi Note 8 Pro is available at: http://127.0.0.1:62833/Db369jd81Ig=/
[ +836 ms] E/ion     ( 7463): ioctl c0044901 failed with code -1: Invalid argument
[  +29 ms] The Flutter DevTools debugger and profiler on Redmi Note 8 Pro is available at: http://127.0.0.1:9102?uri=http://127.0.0.1:62833/Db369jd81Ig=/
[+2168 ms] I/BufferQueueConsumer( 7463): [](id:1d2700000000,api:0,p:-1,c:7463) connect(): controlledByApp=true
[  +23 ms] V/PhoneWindow( 7463): DecorView setVisiblity: visibility = 0, Parent = android.view.ViewRootImpl@9d812f7, this = DecorView@8d18564[MainActivity]
[  +13 ms] I/BufferQueueConsumer( 7463): [](id:1d2700000001,api:0,p:-1,c:7463) connect(): controlledByApp=true
[        ] W/Camera  ( 7463): The selected imageFormatGroup is not supported by Android. Defaulting to yuv420
[        ] I/BufferQueueConsumer( 7463): [](id:1d2700000002,api:0,p:-1,c:7463) connect(): controlledByApp=true
[   +3 ms] E/libc    ( 7463): Access denied finding property "persist.vendor.camera.privapp.list"
[   +7 ms] E/CameraManagerGlobal( 7463): Camera 61 is not available. Ignore physical camera status change
[   +5 ms] W/CameraManagerGlobal( 7463): ignore the torch status update of camera: 21
[        ] W/CameraManagerGlobal( 7463): ignore the torch status update of camera: 22
[        ] W/CameraManagerGlobal( 7463): ignore the torch status update of camera: 61
[   +3 ms] I/Camera  ( 7463): startPreview
[  +87 ms] I/BufferQueueProducer( 7463): [SurfaceTexture-0-7463-0](id:1d2700000000,api:4,p:845,c:7463) connect(): api=4 producerControlledByApp=true
[        ] I/BufferQueueProducer( 7463): [ImageReader-640x480f100m1-7463-0](id:1d2700000001,api:4,p:845,c:7463) connect(): api=4
producerControlledByApp=false
[   +5 ms] I/Camera  ( 7463): CameraCaptureSession onConfigured
[        ] I/Camera  ( 7463): Updating builder settings
[        ] D/Camera  ( 7463): Updating builder with feature: ExposureLockFeature
[        ] D/Camera  ( 7463): Updating builder with feature: ExposurePointFeature
[        ] D/Camera  ( 7463): Updating builder with feature: ZoomLevelFeature
[        ] D/Camera  ( 7463): Updating builder with feature: AutoFocusFeature
[        ] D/Camera  ( 7463): Updating builder with feature: NoiseReductionFeature
[        ] I/Camera  ( 7463): updateNoiseReduction | currentSetting: fast
[        ] D/Camera  ( 7463): Updating builder with feature: FocusPointFeature
[        ] D/Camera  ( 7463): Updating builder with feature: ResolutionFeature
[        ] D/Camera  ( 7463): Updating builder with feature: SensorOrientationFeature
[        ] D/Camera  ( 7463): Updating builder with feature: FlashFeature
[        ] D/Camera  ( 7463): Updating builder with feature: ExposureOffsetFeature
[   +1 ms] D/Camera  ( 7463): Updating builder with feature: FpsRangeFeature
[        ] I/Camera  ( 7463): refreshPreviewCaptureSession
[ +400 ms] I/mali_config( 7463): @get_buffer_dataspace_setting: update dataspace (0x10020000 -> 0x08020000)
[  +66 ms] I/mali_config( 7463): @get_buffer_dataspace_setting: update dataspace (0x10020000 -> 0x08020000)
[  +83 ms] I/mali_config( 7463): @get_buffer_dataspace_setting: update dataspace (0x10020000 -> 0x08020000)
[  +66 ms] I/mali_config( 7463): @get_buffer_dataspace_setting: update dataspace (0x10020000 -> 0x08020000)
[  +66 ms] I/mali_config( 7463): @get_buffer_dataspace_setting: update dataspace (0x10020000 -> 0x08020000)
[  +66 ms] I/mali_config( 7463): @get_buffer_dataspace_setting: update dataspace (0x10020000 -> 0x08020000)
[ +451 ms] I/mali_config( 7463): @get_buffer_dataspace_setting: update dataspace (0x10020000 -> 0x08020000)
[ +586 ms] I/mali_config( 7463): @get_buffer_dataspace_setting: update dataspace (0x10020000 -> 0x08020000)
[+2107 ms] I/r_application_( 7463): ProcessProfilingInfo new_methods=0 is saved saved_to_disk=0 resolve_classes_delay=8000
[ +378 ms] I/Camera  ( 7463): runPictureAutoFocus
[        ] I/Camera  ( 7463): lockAutoFocus
[   +7 ms] D/CameraCaptureCallback( 7463): CameraCaptureCallback | state: STATE_WAITING_FOCUS | afState: 2 | aeState: 2
[   +7 ms] D/CameraCaptureCallback( 7463): CameraCaptureCallback | state: STATE_WAITING_FOCUS | afState: 2 | aeState: 2
[   +7 ms] D/CameraCaptureCallback( 7463): CameraCaptureCallback | state: STATE_WAITING_FOCUS | afState: null | aeState: null
[  +21 ms] D/CameraCaptureCallback( 7463): CameraCaptureCallback | state: STATE_WAITING_FOCUS | afState: 2 | aeState: 2
[   +6 ms] D/CameraCaptureCallback( 7463): CameraCaptureCallback | state: STATE_WAITING_FOCUS | afState: 2 | aeState: 2
[   +8 ms] D/CameraCaptureCallback( 7463): CameraCaptureCallback | state: STATE_WAITING_FOCUS | afState: null | aeState: null
[  +18 ms] D/CameraCaptureCallback( 7463): CameraCaptureCallback | state: STATE_WAITING_FOCUS | afState: 2 | aeState: 2
[  +11 ms] D/CameraCaptureCallback( 7463): CameraCaptureCallback | state: STATE_WAITING_FOCUS | afState: 2 | aeState: 2
[   +7 ms] D/CameraCaptureCallback( 7463): CameraCaptureCallback | state: STATE_WAITING_FOCUS | afState: null | aeState: null
[  +18 ms] D/CameraCaptureCallback( 7463): CameraCaptureCallback | state: STATE_WAITING_FOCUS | afState: 2 | aeState: 2
[  +12 ms] D/CameraCaptureCallback( 7463): CameraCaptureCallback | state: STATE_WAITING_FOCUS | afState: 2 | aeState: 2
[   +5 ms] D/CameraCaptureCallback( 7463): CameraCaptureCallback | state: STATE_WAITING_FOCUS | afState: null | aeState: null
[  +14 ms] D/CameraCaptureCallback( 7463): CameraCaptureCallback | state: STATE_WAITING_FOCUS | afState: 2 | aeState: 2
[   +6 ms] D/CameraCaptureCallback( 7463): CameraCaptureCallback | state: STATE_WAITING_FOCUS | afState: 2 | aeState: 2
[   +8 ms] D/CameraCaptureCallback( 7463): CameraCaptureCallback | state: STATE_WAITING_FOCUS | afState: null | aeState: null
[  +24 ms] D/CameraCaptureCallback( 7463): CameraCaptureCallback | state: STATE_WAITING_FOCUS | afState: 2 | aeState: 2

flutter doctor -v
[✓] Flutter (Channel stable, 3.3.3, on macOS 12.6 21G115 darwin-arm, locale en-AU)
    • Flutter version 3.3.3 on channel stable at /Users/ssheromova/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 18a827f393 (3 weeks ago), 2022-09-28 10:03:14 -0700
    • Engine revision 5c984c26eb
    • Dart version 2.18.2
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at /Users/ssheromova/Library/Android/sdk
    • Platform android-33, build-tools 33.0.0
    • ANDROID_HOME = /Users/ssheromova/Library/Android/sdk
    • Java binary at: /Users/ssheromova/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/212.5712.43.2112.8815526/Android
      Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.0.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14A400
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.2)
    • Android Studio at /Users/ssheromova/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/212.5712.43.2112.8815526/Android
      Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)

[✓] VS Code (version 1.72.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.50.0

[✓] Connected device (4 available)
    • Redmi Note 8 Pro (mobile) • rkda597hcqdm7pfq                     • android-arm64  • Android 11 (API 30)
    • iPhone 13 mini (mobile)   • 0093DF38-785E-4BCF-B58C-6AE49ED2D75D • ios            • com.apple.CoreSimulator.SimRuntime.iOS-16-0 (simulator)
    • macOS (desktop)           • macos                                • darwin-arm64   • macOS 12.6 21G115 darwin-arm
    • Chrome (web)              • chrome                               • web-javascript • Google Chrome 106.0.5249.119

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2Important issues not at the top of the work listfound in release: 3.3Found to occur in 3.3found in release: 3.5Found to occur in 3.5has reproducible stepsThe issue has been confirmed reproducible and is ready to work onp: cameraThe camera pluginpackageflutter/packages repository. See also p: labels.platform-androidAndroid applications specificallyteam-androidOwned by Android platform teamtriaged-androidTriaged by Android platform team

    Type

    No type

    Projects

    • Status
      [PENDING] camera_android issues solved by camera_android_camerax

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions