Code Monkey home page Code Monkey logo

Comments (2)

abdullah432 avatar abdullah432 commented on September 25, 2024

Ok. I found the solution. Their is bug in plugin. New plugin is not registering. Means They call following code to register plugin but it's not working.
projectname\android\app\src\main\java\io\flutter\plugins/GeneratedPluginRegistrant

public final class GeneratedPluginRegistrant {
  public static void registerWith(@NonNull FlutterEngine flutterEngine) {
    ShimPluginRegistry shimPluginRegistry = new ShimPluginRegistry(flutterEngine);
      com.isvisoft.flutter_screen_recording.FlutterScreenRecordingPlugin.registerWith(shimPluginRegistry.registrarFor("com.isvisoft.flutter_screen_recording.FlutterScreenRecordingPlugin"));
  }
}

Note: this code is only for android.

delete mainactivity.kt file and create MainActivity.java. Then paste following code.

package com.example.**yourpackagename;**

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import java.io.File;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;


public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "flutter_screen_recording";

    private VirtualDisplay mVirtualDisplay;
    private MediaRecorder mMediaRecorder;
    private MediaProjection mMediaProjection;
    MediaProjectionManager mProjectionManager;
    private MediaProjectionCallback mediaProjectionCallback;
    private int SCREEN_RECORD_REQUEST_CODE = 333;
    private String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() + File.separator;
    private String videoName;
    int mDisplayWidth = 1280;
    int mDisplayHeight = 800;
    int mScreenDensity = 0;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
                .setMethodCallHandler(
                        (call, result) -> {
                            if (call.method.equals("startRecordScreen")){
                                try{
                                    mMediaRecorder = new MediaRecorder();
                                    mProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
                                    DisplayMetrics metrics = new DisplayMetrics();
                                    WindowManager windowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
                                    windowManager.getDefaultDisplay().getMetrics(metrics);
                                    mScreenDensity = metrics.densityDpi;
                                    mDisplayWidth = Math.round(metrics.widthPixels / metrics.scaledDensity);
                                    mDisplayHeight = Math.round(metrics.heightPixels / metrics.scaledDensity);
                                    videoName = call.arguments.toString();
                                    Log.i("videoname: ",videoName);
                                    startRecordScreen();
                                    result.success(true);
                                }catch (Exception e){
                                    result.success(false);
                                }
                            }else if (call.method.equals("stopRecordScreen")) {
                                if(mMediaProjection != null){
                                    stopRecordScreen();
                                    result.success(path+videoName+".mp4");
                                    stopScreenSharing();
                                }else{
                                    result.success("");
                                }


                            }else if (call.method.equals("getPlatformVersion")) {
                                result.success("Android ${android.os.Build.VERSION.RELEASE}");
                            } else {
                                result.notImplemented();
                            }
                        }
                );
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    void startRecordScreen() {
        initRecorder();
        Intent permissionIntent = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            permissionIntent = mProjectionManager.createScreenCaptureIntent();
            ActivityCompat.startActivityForResult(this, permissionIntent, SCREEN_RECORD_REQUEST_CODE, null);
        }
//        ActivityCompat.startActivityForResult((registrar.context().applicationContext as FlutterApplication).currentActivity, permissionIntent!!, SCREEN_RECORD_REQUEST_CODE, null)

    }

    private void stopRecordScreen() {
        mMediaRecorder.stop();
        // mMediaRecorder.reset();
        mMediaRecorder.release();
//        mMediaProjection = null;
//        mMediaRecorder = null;
    }

    private void stopScreenSharing(){
        if(mVirtualDisplay != null){
            mVirtualDisplay.release();
            destroyMediaProjection();
        }
    }

    private void destroyMediaProjection() {
        if (mMediaProjection != null) {
            mMediaProjection.unregisterCallback(mediaProjectionCallback);
            mMediaProjection.stop();
            mMediaProjection = null;
        }
        Log.d("TAG", "MediaProjection Stopped");
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void initRecorder() {
//        recId = "capture-" + System.currentTimeMillis() + ".mp4";
//        File myDirectory = new File(Environment.getExternalStorageDirectory(), "Record");
        try{
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mMediaRecorder.setVideoEncodingBitRate(5 * mDisplayWidth * mDisplayHeight);
            mMediaRecorder.setVideoFrameRate(30);
            mMediaRecorder.setVideoSize(mDisplayWidth, mDisplayHeight);
            mMediaRecorder.setOutputFile(path+videoName+".mp4");
            mMediaRecorder.prepare();
        }catch (Exception e){
            Log.d("Init recorder", e.getMessage());
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public class MediaProjectionCallback extends MediaProjection.Callback {
        @Override
        public void onStop() {
            mMediaRecorder.stop();
            // mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaProjection.unregisterCallback(mediaProjectionCallback);
            mMediaProjection = null;
            mMediaRecorder = null;
        }
        }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SCREEN_RECORD_REQUEST_CODE){
            if (resultCode == Activity.RESULT_OK){
                mediaProjectionCallback = new MediaProjectionCallback();
//                getSystemService(Context.MEDIA_PROJECTION_SERVICE);
                mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
                mMediaProjection.registerCallback(mediaProjectionCallback, null);
                mVirtualDisplay = createVirtualDisplay();
                mMediaRecorder.start();
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private VirtualDisplay createVirtualDisplay() {
        return mMediaProjection.createVirtualDisplay("MainActivity",
                mDisplayWidth, mDisplayHeight, mScreenDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mMediaRecorder.getSurface(), null /*Callbacks*/, null /*Handler*/);
    }
}

create new class in lab folder to access native code.

import 'dart:async';

import 'package:flutter/services.dart';

class FlutterScreenRecording {
  static const MethodChannel _channel =
  const MethodChannel('flutter_screen_recording');

  static Future<String> get platformVersion async {
    final String version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  static Future<bool> startRecordScreen(String name) async {
    final bool start = await _channel.invokeMethod('startRecordScreen', name);
    return start;
  }

  static Future<String> get stopRecordScreen async {
    final String path =  await _channel.invokeMethod('stopRecordScreen');
    return path;
  }
}

Now use it. It will work fine.

from flutter_screen_recording.

salime45 avatar salime45 commented on September 25, 2024

In the last version, this is fixed

from flutter_screen_recording.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.