/** * Creates a streaming session that can be customized by adding tracks. */ public Session() { long uptime = Java.Lang.JavaSystem.CurrentTimeMillis(); HandlerThread thread = new HandlerThread("Net.Majorkernelpanic.Streaming.Session"); thread.Start(); mHandler = new Handler(thread.Looper); mMainHandler = new Handler(Looper.MainLooper); mTimestamp = (uptime / 1000) << 32 & (((uptime - ((uptime / 1000) * 1000)) >> 32) / 1000); // NTP timestamp mOrigin = "127.0.0.1"; mUpdateBitrate = new Runnable(() => { void Run() { if (isStreaming()) { postBitRate(getBitrate()); mHandler.PostDelayed(mUpdateBitrate, 500); } else { postBitRate(0); } } }); }
private void UpdatePreview() { if (cameraDevice != null && cameraCaptureSession != null) { try { captureRequestBuilder.Set(CaptureRequest.ControlMode, new Java.Lang.Integer((int)ControlMode.Auto)); HandlerThread thread = new HandlerThread("CameraPicture"); thread.Start(); Handler backgroundHandler = new Handler(thread.Looper); cameraCaptureSession.SetRepeatingRequest(captureRequestBuilder.Build(), null, backgroundHandler); } catch (CameraAccessException error) { ShowToastMessage("Failed to access camera"); DebugMessage("ErrorMessage: \n" + error.Message + "\n" + "Stacktrace: \n " + error.StackTrace); } catch (IllegalStateException error) { ShowToastMessage("Failed to access camera"); DebugMessage("ErrorMessage: \n" + error.Message + "\n" + "Stacktrace: \n " + error.StackTrace); } } }
private void Startbackgroundthread() { Thread = new HandlerThread("Camera Background"); Thread.Start(); Handler = new Handler(Thread.Looper); //throw new NotImplementedException(); }
/// <summary> /// Opens the camera. /// </summary> public void OpenCamera() { if (_context == null || OpeningCamera) { return; } OpeningCamera = true; _manager = (CameraManager)_context.GetSystemService(Context.CameraService); try { string cameraId = _manager.GetCameraIdList()[0]; // To get a list of available sizes of camera preview, we retrieve an instance of // StreamConfigurationMap from CameraCharacteristics CameraCharacteristics characteristics = _manager.GetCameraCharacteristics(cameraId); StreamConfigurationMap map = (StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap); _previewSize = map.GetOutputSizes(Java.Lang.Class.FromType(typeof(SurfaceTexture)))[0]; Android.Content.Res.Orientation orientation = Resources.Configuration.Orientation; if (orientation == Android.Content.Res.Orientation.Landscape) { _cameraTexture.SetAspectRatio(_previewSize.Width, _previewSize.Height); } else { _cameraTexture.SetAspectRatio(_previewSize.Height, _previewSize.Width); } HandlerThread thread = new HandlerThread("CameraPreview"); thread.Start(); Handler backgroundHandler = new Handler(thread.Looper); // We are opening the camera with a listener. When it is ready, OnOpened of mStateListener is called. _manager.OpenCamera(cameraId, _stateListener, null); } catch (Java.Lang.Exception error) { _log.WriteLineTime(_tag + "\n" + "OpenCamera() Failed to open camera \n " + "ErrorMessage: \n" + error.Message + "\n" + "Stacktrace: \n " + error.StackTrace); Available?.Invoke(this, false); } catch (System.Exception error) { _log.WriteLineTime(_tag + "\n" + "OpenCamera() Failed to open camera \n " + "ErrorMessage: \n" + error.Message + "\n" + "Stacktrace: \n " + error.StackTrace); Available?.Invoke(this, false); } }
public override void OnCreate() { var thread = new HandlerThread("RegressionTestService", Process.THREAD_PRIORITY_BACKGROUND); thread.Start(); handler = new ServiceHandler(thread.Looper); }
void UpdatePreview() { if (ActiveCameraDevice == null || ActiveCaptureSession == null) { return; } try { // The camera preview can be run in a background thread. This is a Handler for the camere preview SetUpCaptureRequestBuilder(previewBuilder); HandlerThread thread = new HandlerThread("CameraPreview"); thread.Start(); Handler backgroundHandler = new Handler(thread.Looper); // We start displaying the camera preview ActiveCaptureSession.SetRepeatingRequest(previewBuilder.Build(), null, backgroundHandler); } catch (CameraAccessException ex) { Log.WriteLine(LogPriority.Info, "Camera2BasicFragment", ex.StackTrace); } catch (Java.Lang.IllegalStateException ex) { Log.WriteLine(LogPriority.Info, "Camera2BasicFragment", ex.StackTrace); } }
public WidgetProvider() { // Start the worker thread workerThread = new HandlerThread (ThreadWorkerName); workerThread.Start(); workerQueue = new Handler (workerThread.Looper); }
public void StartPreview() { if (liveTextureView.SurfaceTexture == null) { return; } var texture = liveTextureView.SurfaceTexture; texture.SetDefaultBufferSize(previewSize.Width, previewSize.Height); var surface = new Surface(texture); previewBuilder = CameraDevice.CreateCaptureRequest(CameraTemplate.Preview); previewBuilder.AddTarget(surface); CameraDevice.CreateCaptureSession(new List <Surface> { surface }, new CameraCaptureStateListener { OnConfigureFailedAction = (CameraCaptureSession session) => { }, OnConfiguredAction = (CameraCaptureSession session) => { previewSession = session; previewBuilder.Set(CaptureRequest.ControlMode, new Java.Lang.Integer((int)ControlMode.Auto)); var thread = new HandlerThread("CameraPicture"); thread.Start(); var backgroundHandler = new Handler(thread.Looper); previewSession.SetRepeatingRequest(previewBuilder.Build(), null, backgroundHandler); } }, null); }
private void StartBackgroundThread() { BackgroundThread = new HandlerThread("CameraPreviewWorkThread"); BackgroundThread.Start(); Logger.Log("Camera thread is start"); BackgroundHandler = new Handler(BackgroundThread.Looper); }
/// <inheritdoc /> public override void OnCreate() { _fusedLocationClient = LocationServices.GetFusedLocationProviderClient(this); _locationCallback = new LocationCallback(); _locationCallback.LocationResult += (sender, args) => OnNewLocation(args.Result.LastLocation); CreateLocationRequest(); GetLastLocation(); var handlerThread = new HandlerThread(Tag); handlerThread.Start(); _serviceHandler = new Handler(handlerThread.Looper); _notificationManager = (NotificationManager)GetSystemService(NotificationService); // Android O requires a Notification Channel. if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { var name = GetString(Resource.String.app_name); // Create the channel for the notification var mChannel = new NotificationChannel(ChannelId, name, NotificationImportance.Low); // Set the Notification Channel for the Notification Manager. _notificationManager.CreateNotificationChannel(mChannel); } }
public bool setup(DecoderCallback callback_obj, int width, int height) //format_hint is aviFileContent { callbackThread = new HandlerThread("H264DecoderHandler"); callbackThread.Start(); handler = new Handler(callbackThread.Looper); mDecoder = MediaCodec.CreateDecoderByType(MIME); mCallbackObj = callback_obj; myCallback = new MyCallback(mDecoder, mCallbackObj); mDecoder.SetCallback(myCallback, handler); //mOutputFormat = mDecoder.GetOutputFormat(); // option B inputFormat = MediaFormat.CreateVideoFormat(MIME, width, height); inputFormat.SetInteger(MediaFormat.KeyMaxInputSize, width * height); inputFormat.SetInteger("durationUs", 63446722); //inputFormat.SetInteger(MediaFormat.KeyColorFormat, (int)MediaCodecCapabilities.Formatyuv420semiplanar); //inputFormat.SetInteger(MediaFormat.KeyIFrameInterval, 60); try { mDecoder.Configure(inputFormat, null, null, 0 /* Decoder */); } catch (Exception ex) { throw ex; } Console.WriteLine("before mDecoder.Start()"); mDecoder.Start(); Console.WriteLine("after mDecoder.Start()"); return(true); }
public WidgetProvider() { // Start the worker thread workerThread = new HandlerThread(ThreadWorkerName); workerThread.Start(); workerQueue = new Handler(workerThread.Looper); }
protected override void OnResume() { base.OnResume(); _orientationListener.Enable(); if (TextureView == null) { throw new InvalidOperationException(string.Format("'{0}' must be set within '{1}'", nameof(TextureView), nameof(OnCreate))); } // start background thread: _backgroundThread = new HandlerThread(nameof(AndroidCameraActivity)); _backgroundThread.Start(); _backgroundHandler = new Handler(_backgroundThread.Looper); if (TextureView.IsAvailable) { OpenCamera(); } else { TextureView.SurfaceTextureListener = this; } }
public RichPushWidgetProvider() { // Start the worker thread workerThread = new HandlerThread("RichPushSampleInbox-Provider"); workerThread.Start(); workerQueue = new Handler(workerThread.Looper); }
/// <summary> /// Updates the camera preview, StartPreview() needs to be called in advance /// </summary> private void UpdatePreview() { if (_cameraDevice != null && _previewSession != null) { try { // The camera preview can be run in a background thread. This is a Handler for the camere preview _previewBuilder.Set(CaptureRequest.ControlMode, new Java.Lang.Integer((int)ControlMode.Auto)); // We create a Handler since we want to handle the resulting JPEG in a background thread HandlerThread thread = new HandlerThread("CameraPicture"); thread.Start(); Handler backgroundHandler = new Handler(thread.Looper); // Finally, we start displaying the camera preview //if (_previewSession.IsReprocessable) _previewSession.SetRepeatingRequest(_previewBuilder.Build(), null, backgroundHandler); } catch (CameraAccessException error) { Log.WriteLine(LogPriority.Error, error.Source, error.Message); } catch (IllegalStateException error) { Log.WriteLine(LogPriority.Error, error.Source, error.Message); } } }
public PhotoUploader() { _handlerThread = new HandlerThread("MyPhotoUploader"); _handlerThread.Start(); _uploadHandler = new Handler(_handlerThread.Looper); }
public void TakePhoto() { var characteristics = cameraManager.GetCameraCharacteristics(CameraDevice.Id); var jpegSizes = ((StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.Jpeg); var width = jpegSizes[0].Width; var height = jpegSizes[0].Height; var reader = ImageReader.NewInstance(width, height, ImageFormatType.Jpeg, 1); var outputSurfaces = new List <Surface> { reader.Surface }; CaptureRequest.Builder captureBuilder = CameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture); captureBuilder.AddTarget(reader.Surface); captureBuilder.Set(CaptureRequest.ControlMode, (int)ControlMode.Auto); // Orientation var windowManager = Context.GetSystemService(Context.WindowService).JavaCast <IWindowManager>(); SurfaceOrientation rotation = windowManager.DefaultDisplay.Rotation; captureBuilder.Set(CaptureRequest.JpegOrientation, orientation); var readerListener = new ImageAvailableListener(); readerListener.Photo += (sender, e) => { (Element as Controls.CameraPage).SetPhotoResult(e, width, height); }; HandlerThread thread = new HandlerThread("CameraPicture"); thread.Start(); Handler backgroundHandler = new Handler(thread.Looper); reader.SetOnImageAvailableListener(readerListener, backgroundHandler); var captureListener = new CameraCaptureListener(); captureListener.PhotoComplete += (sender, e) => { StartPreview(); }; CameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureStateListener() { OnConfiguredAction = (CameraCaptureSession session) => { try { previewSession = session; session.Capture(captureBuilder.Build(), captureListener, backgroundHandler); } catch (CameraAccessException ex) { Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString()); } } }, backgroundHandler); }
// Token: 0x06000460 RID: 1120 RVA: 0x0001DCF8 File Offset: 0x0001BEF8 public InventoryService() { this.accompainimentRunnable = new Runnable(new Action(this.StartAccompanitment)); HandlerThread handlerThread = new HandlerThread(""); handlerThread.Start(); this.accompainimentsHandler = new Handler(handlerThread.Looper); }
public void StartPeriodic(CancellationToken cancellationToken) { _cancellationToken = cancellationToken; _handlerThread = new HandlerThread(_service.Name, (int)ThreadPriority.Background); _handlerThread.Start(); _handler = new Handler(_handlerThread.Looper); ScheduleNext(); }
/// <summary> /// Starts a background thread and its {@link Handler}. /// </summary> void StartBackgroundThread() { mBackgroundThread = new HandlerThread("CameraBackground"); mBackgroundThread.Start(); lock (mCameraStateLock) { mBackgroundHandler = new Handler(mBackgroundThread.Looper); } }
/// <summary> /// The on create. /// </summary> public override void OnCreate() { base.OnCreate(); var localHandlerThread = new HandlerThread("IntentService[" + this.name + "]"); localHandlerThread.Start(); this.serviceLooper = localHandlerThread.Looper; this.serviceHandler = new ServiceHandler(this.serviceLooper, this); }
/// <summary> /// Starts a background thread and its {@link Handler}. /// </summary> public void StartBackgroundThread() { if (backgroundThread == null) { backgroundThread = new HandlerThread("CameraBackground"); backgroundThread.Start(); backgroundHandler = new Handler(backgroundThread.Looper); } }
/// <summary> /// Starts a background thread and its {@link Handler}. /// </summary> public void StartBackgroundThread() { _backgroundThread = new HandlerThread("CameraBackground"); _backgroundThread.Start(); lock (_cameraStateLock) { _backgroundHandler = new Handler(_backgroundThread.Looper); } }
Handler GetHandlerThreadHandler() { if (Handler == null) { HandlerThread handlerThread = new HandlerThread("fonts"); handlerThread.Start(); Handler = new Handler(handlerThread.Looper); } return(Handler); }
private void StartBackgroundThread() { if (backgroundThread != null) { StopBackgroundThread(); } backgroundThread = new HandlerThread("CameraBackground"); backgroundThread.Start(); backgroundHandler = new Handler(backgroundThread.Looper); }
private void OpenCamera() { if (CheckSelfPermission(Manifest.Permission.Camera) != Permission.Granted) { RequestCameraPermission(); return; } camera = Open(); Parameters parameters = camera.GetParameters(); parameters.PictureFormat = ImageFormatType.Jpeg; parameters.PreviewFormat = ImageFormatType.Nv21; if (parameters.SupportedFocusModes.Contains(Parameters.FocusModeContinuousVideo)) { parameters.FocusMode = Parameters.FocusModeContinuousVideo; } IList <Size> suportedPreviewSizes = parameters.SupportedPreviewSizes; int i = 0; for (i = 0; i < suportedPreviewSizes.Count; i++) { if (suportedPreviewSizes[i].Width < 1300) { break; } } parameters.SetPreviewSize(suportedPreviewSizes[i].Width, suportedPreviewSizes[i].Height); camera.SetParameters(parameters); camera.SetDisplayOrientation(90); camera.SetPreviewCallback(this); camera.SetPreviewDisplay(surface.Holder); camera.StartPreview(); //Get camera width previewWidth = parameters.PreviewSize.Width; //Get camera height previewHeight = parameters.PreviewSize.Height; //Resize SurfaceView Size float scaledHeight = previewWidth * 1.0f * surface.Width / previewHeight; float prevHeight = surface.Height; ViewGroup.LayoutParams lp = surface.LayoutParameters; lp.Width = surface.Width; lp.Height = (int)scaledHeight; surface.LayoutParameters = lp; surface.Top = (int)((prevHeight - scaledHeight) / 2); surface.DrawingCacheEnabled = true; handlerThread = new HandlerThread("background"); handlerThread.Start(); //backgroundHandler = new MyHandler(handlerThread.Looper); backgroundHandler = new MyHandler(Looper.MainLooper); }
public void start() { LogUtil.init(); ImageSource.addOnFrameAvailableListener(onFrameAvailableListener); processThread = new HandlerThread("process"); processThread.Priority = 9; processThread.Start(); processHandler = new Handler(processThread.Looper); uiHandler = new Handler(); ImageSource.start(); }
/** Starts a background thread and its {@link Handler}. */ private void startBackgroundThread() { backgroundThread = new HandlerThread(HANDLE_THREAD_NAME); backgroundThread.Start(); backgroundHandler = new Handler(backgroundThread.Looper); lock (@lock) { runClassifier = true; } backgroundHandler.Post(periodicClassify); }
/// <summary> /// Start the camera thread. /// </summary> private void StartCameraThread() { mCameraThread = new HandlerThread("CameraThread"); mCameraThread.Start(); if (mCameraThread.Looper != null) { Log.Debug(TAG, "startCameraThread mCameraThread.Looper null!"); return; } mCameraHandler = new Handler(mCameraThread.Looper); }
private void StartHandlerThread() { if (_handlerThread != null) { StopHandlerThread(); } _handlerThread = new HandlerThread("PeriodicServiceThread", (int)ThreadPriority.Background); _handlerThread.Start(); _handler = new Handler(_handlerThread.Looper); ScheduleNext(); }
public MyCameraCallback(Surface surface, CameraPreviewView cameraPreviewView) { _surface = surface; _cameraPreviewView = cameraPreviewView; _reader = ImageReader.NewInstance(800, 450, ImageFormatType.Jpeg, 1); var stillImageListener = new StillImageListener(cameraPreviewView); HandlerThread handlerThread = new HandlerThread("CameraWorker"); handlerThread.Start(); _reader.SetOnImageAvailableListener(stillImageListener, new Handler(handlerThread.Looper)); }
//Update the preview public void updatePreview() { if (null == cameraDevice) return; try { setUpCaptureRequestBuilder(previewBuilder); HandlerThread thread = new HandlerThread("CameraPreview"); thread.Start(); previewSession.SetRepeatingRequest(previewBuilder.Build(),null,backgroundHandler); } catch(CameraAccessException e) { e.PrintStackTrace (); } }
/// <summary> /// The on create. /// </summary> public override void OnCreate() { base.OnCreate(); var localHandlerThread = new HandlerThread("IntentService[" + this.name + "]"); localHandlerThread.Start(); this.serviceLooper = localHandlerThread.Looper; this.serviceHandler = new ServiceHandler(this.serviceLooper, this); }
private void StartBackgroundThread() { backgroundThread = new HandlerThread ("CameraBackground"); backgroundThread.Start (); backgroundHandler = new Handler (backgroundThread.Looper); }
private List<GeoPoint> Simplify(MapView mapView, List<GeoPoint> data) { if (ShouldSimplify) { if (_simplifierHandler == null || _simplifierThread == null) { _simplifierThread = new HandlerThread("simplifier", 1); _simplifierThread.Start(); _simplifierHandler = new SimplifierHandler(mapView, _simplifierThread.Looper, new List<Point>(), data, _simplificationEpsilon); } if (_simplfied == null) { _simplfied = new List<List<GeoPoint>>(); mapView.Post(new Simplifier(mapView.Projection, null, null, _simplifierHandler)); } //else if (_simplified.Count != 0) //{ // data = this.simplified; //} } return data; }
/// <summary> /// Initializes a new instance of the <see cref="LicenseChecker"/> class. /// The license checker. /// </summary> /// <param name="context"> /// a Context /// </param> /// <param name="policy"> /// implementation of IPolicy /// </param> /// <param name="encodedPublicKey"> /// Base64-encoded RSA public key /// </param> /// <exception cref="ArgumentException"> /// if encodedPublicKey is invalid /// </exception> public LicenseChecker(Context context, IPolicy policy, string encodedPublicKey) { this.locker = new object(); this.checksInProgress = new HashSet<LicenseValidator>(); this.pendingChecks = new Queue<LicenseValidator>(); this.context = context; this.policy = policy; this.publicKey = GeneratePublicKey(encodedPublicKey); this.packageName = this.context.PackageName; this.versionCode = GetVersionCode(context, this.packageName); var handlerThread = new HandlerThread("background thread"); handlerThread.Start(); this.handler = new Handler(handlerThread.Looper); }
public RichPushWidgetProvider() { // Start the worker thread workerThread = new HandlerThread("RichPushSampleInbox-Provider"); workerThread.Start(); workerQueue = new Handler (workerThread.Looper); }
public static TestContentObserver getTestContentObserver () { HandlerThread ht = new HandlerThread ("ContentObserverThread"); ht.Start (); return new TestContentObserver (ht); }
public override void OnCreate() { // TODO: It would be nice to have an option to hold a partial wakelock // during processing, and to have a static startService(Context, Intent) // method that would launch the service & hand off a wakelock. base.OnCreate(); HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); thread.Start(); mServiceLooper = thread.Looper; mServiceHandler = new ServiceHandler(mServiceLooper, this); }
public override void OnCreate() { base.OnCreate (); if (prefs == null) prefs = new PreferenceManager (this); var thread = new HandlerThread ("IntentService[BikrActivityService]"); thread.Start (); serviceLooper = thread.Looper; serviceHandler = new ServiceHandler (this, serviceLooper); }
public override void OnCreate() { var thread = new HandlerThread("RegressionTestService", Process.THREAD_PRIORITY_BACKGROUND); thread.Start(); handler = new ServiceHandler(thread.Looper); }
private void TakePicture() { try { Activity activity = Activity; if(activity == null|| mCameraDevice == null) return; Size[] jpegSizes = null; if(cCharacteristics != null) jpegSizes = ((StreamConfigurationMap) cCharacteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.Jpeg); int width = 640; int height = 480; if(jpegSizes != null && jpegSizes.Length > 0) { width = jpegSizes[0].Width; height = jpegSizes[0].Height; } //ImageReader reader = ImageReader.NewInstance(width,height,ImageFormatType.Jpeg, 1); ImageReader multiReader = ImageReader.NewInstance(width,height,ImageFormatType.Jpeg, 1000); List<Surface> outputSurfaces = new List<Surface>(3); //outputSurfaces.Add(reader.Surface); outputSurfaces.Add(new Surface(mTextureView.SurfaceTexture)); outputSurfaces.Add(multiReader.Surface); //just take each image and add it to a multiple image Image reader: new imageReader.newInstance(width, height, ImageFormatType.Jpeg, NumberOfImages) CaptureRequest.Builder crBuilder = mCameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture); crBuilder.AddTarget(outputSurfaces[0]); crBuilder.AddTarget(outputSurfaces[1]); //crBuilder.AddTarget(outputSurfaces[2]); SurfaceOrientation rotation = activity.WindowManager.DefaultDisplay.Rotation; crBuilder.Set(CaptureRequest.JpegOrientation, new Java.Lang.Integer(ORIENTATIONS.Get((int)rotation))); File file = new File(activity.GetExternalFilesDir(null), count + ".jpg"); count++; ImageAvailableListener readerListener = new ImageAvailableListener() { File = file };; HandlerThread thread = new HandlerThread("CameraPicture"); thread.Start(); Handler backgroundHandler = new Handler(thread.Looper); multiReader.SetOnImageAvailableListener(readerListener, backgroundHandler); CameraCaptureListener captureListener = new CameraCaptureListener() {Fragment = this, File = file}; mCameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureStateListener() { OnConfiguredAction = (CameraCaptureSession session) => { try { List<CaptureRequest> requests = new List<CaptureRequest>(); float distance = (float)cCharacteristics.Get(CameraCharacteristics.LensInfoMinimumFocusDistance); //for(float distance = (float)cCharacteristics.Get(CameraCharacteristics.LensInfoMinimumFocusDistance); distance > 0.00769230769; distance /= 2) for(int i = 0; i < 10; i++) { //crBuilder.Set(CaptureRequest.LensFocusDistance, distance); requests.Add(crBuilder.Build()); Log.Debug("CaptureRequest", "Added new captureRequst"); } session.CaptureBurst(requests, captureListener, backgroundHandler); Toast.MakeText (activity, "BurstCapture Complete", ToastLength.Long).Show (); //session.Capture(crBuilder.Build(), captureListener, backgroundHandler); } catch (CameraAccessException ex) { Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString()); } } }, backgroundHandler ); } catch (CameraAccessException ex) { Log.WriteLine (LogPriority.Info, "Taking Picture error: ", ex.StackTrace); } }
private void UpdatePreview() { if (mCameraDevice == null) return; try { SetUpCaptureRequestBuilder(mPreviewBuilder); HandlerThread thread = new HandlerThread("CameraPreview"); thread.Start(); Handler backgroundHandler = new Handler(thread.Looper); mPreviewSession.SetRepeatingRequest(mPreviewBuilder.Build(), null ,backgroundHandler); } catch (CameraAccessException ex) { Log.WriteLine (LogPriority.Info, "CameraFragment: Preview Update", ex.StackTrace); } }
/// <summary> /// Updates the camera preview, StartPreview() needs to be called in advance /// </summary> private void UpdatePreview() { if (mCameraDevice == null) { return; } try { // The camera preview can be run in a background thread. This is a Handler for the camere preview SetUpCaptureRequestBuilder(mPreviewBuilder); HandlerThread thread = new HandlerThread("CameraPreview"); thread.Start(); Handler backgroundHandler = new Handler(thread.Looper); // Finally, we start displaying the camera preview mPreviewSession.SetRepeatingRequest(mPreviewBuilder.Build(), null, backgroundHandler); } catch (Exception ex) { Log.WriteLine (LogPriority.Info, "Camera2BasicFragment", ex.StackTrace); } }
/// <summary> /// Takes a picture. /// </summary> private void TakePicture() { try { Activity activity = Activity; if (activity == null || mCameraDevice == null) { return; } CameraManager manager = (CameraManager) activity.GetSystemService(Context.CameraService); // Pick the best JPEG size that can be captures with this CameraDevice CameraCharacteristics characteristics = manager.GetCameraCharacteristics(mCameraDevice.Id); Size[] jpegSizes = null; if (characteristics != null) { jpegSizes = ((StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.Jpeg); } int width = 640; int height = 480; if (jpegSizes != null && jpegSizes.Length > 0) { width = jpegSizes[0].Width; height = jpegSizes[0].Height; } // We use an ImageReader to get a JPEG from CameraDevice // Here, we create a new ImageReader and prepare its Surface as an output from the camera ImageReader reader = ImageReader.NewInstance(width, height, ImageFormatType.Jpeg, 1); List<Surface> outputSurfaces = new List<Surface>(2); outputSurfaces.Add(reader.Surface); outputSurfaces.Add(new Surface(mTextureView.SurfaceTexture)); CaptureRequest.Builder captureBuilder = mCameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture); captureBuilder.AddTarget(reader.Surface); SetUpCaptureRequestBuilder(captureBuilder); // Orientation SurfaceOrientation rotation = activity.WindowManager.DefaultDisplay.Rotation; captureBuilder.Set(CaptureRequest.JpegOrientation, new Java.Lang.Integer(ORIENTATIONS.Get((int)rotation))); // Output file File file = new File(activity.GetExternalFilesDir(null), "pic.jpg"); // This listener is called when an image is ready in ImageReader // Right click on ImageAvailableListener in your IDE and go to its definition ImageAvailableListener readerListener = new ImageAvailableListener() { File = file }; // We create a Handler since we want to handle the resulting JPEG in a background thread HandlerThread thread = new HandlerThread("CameraPicture"); thread.Start(); Handler backgroundHandler = new Handler(thread.Looper); reader.SetOnImageAvailableListener(readerListener, backgroundHandler); //This listener is called when the capture is completed // Note that the JPEG data is not available in this listener, but in the ImageAvailableListener we created above // Right click on CameraCaptureListener in your IDE and go to its definition CameraCaptureListener captureListener = new CameraCaptureListener() { Fragment = this, File = file }; mCameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureStateListener() { OnConfiguredAction = (CameraCaptureSession session) => { try { session.Capture(captureBuilder.Build(), captureListener, backgroundHandler); } catch (Exception ex) { Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString()); } } }, backgroundHandler ); } catch (Exception ex) { Log.WriteLine(LogPriority.Info, "Taking picture error: ", ex.StackTrace); } }