Front Camera2 API GLSurfaceview - android

I'm trying to access the front facing camera through the Camera2 API using an actual device
the problem occurs when trying to
cameraManager.openCamera(..,..,..)
try {
CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraID);
if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Time out waiting to lock camera opening.");
}
manager.openCamera(mCameraID, mStateCallback, mBackgroundHandler);
} catch (CameraAccessException e) {
Log.e("mr", "OpenCamera - Camera Access Exception");
} catch (IllegalArgumentException e) {
Log.e("mr", "OpenCamera - Illegal Argument Exception");
} catch (SecurityException e) {
e.printStackTrace();
Log.e("mr", "OpenCamera - Security Exception:");
} catch (InterruptedException e) {
Log.e("mr", "OpenCamera - Interrupted Exception");
}
the Cameramanager says
I/CameraManagerGlobal: Connecting to camera service
which is coming from this CameraManager.java function
private void connectCameraServiceLocked() {
// Only reconnect if necessary
if (mCameraService != null) return;
Log.i(TAG, "Connecting to camera service");
Then my GLSurfaceView remains blank
AndroidMainfest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.permission.PROVIDE_BACKGROUND" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
P.S:
It works with the back camera
It works with the nexus 6 API 23 emulator
Permissions are requested at runtime for Android M
I'm using GLSurfaceView as a viewfinder
The front camera was working perfectly on the same device using the normal CameraAPI with a TextureView
Tried to Uninstall/Reboot/Clear Cache
the device I'm using is a Sony Z5 premium
I'm using this example Render camera preview using OpenGL ES 2.0 on Android API 21 or higher

If you're just copying that example, I noticed it has the following line:
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
The front camera probably doesn't support that, since it likely has no flash. You need to check what AE modes are actually supported - the same goes for the various other settings the sample sets, where it isn't checking what the device actually supports.
That said, you should be getting an error if the value is bad, but it might be coming in on the CameraCaptureSession.CaptureListener.onCaptureFailed, and the sample is not listening to those. There's probably also some logcat from the camera service, if you look at all logging, not just your own app's logs.
But try removing that line, and see if it works.

I've ended with changing the Sony Xperia Z5 premium to another device and it worked perfectly.
it looks like that Sony is facing some problems with the new API as i saw in the following link:
Sony Camera2 API limitations
there might be a work around but anyway i'm making an application for specific purpose i don't want it to be working on all devices

First get Camera service like this
CameraManager cameraManager = (CameraManager)getSystemService(Context.CAMERA_SERVICE);

Related

How to properly find Physical Camera ID, Android Studio

So I'm trying to get the IDs of the Physical cameras on the phone (Xiaomi Red Mi Note 9). First I'm getting the IDs of the Logical cameras and use those IDs to get some information about the Physical ones, but every time I get "0" Physical cameras.
Here is the code :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if( checkSelfPermission(Manifest.permission.CAMERA)==PackageManager.PERMISSION_GRANTED)
{
cameraManager=(CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
logicalCameraIdS=cameraManager.getCameraIdList();
for(String logicalCameraId :logicalCameraIdS)
{
cameraCharacteristics=cameraManager.getCameraCharacteristics(logicalCameraId);
Set<String> physicalCameraIdS=cameraCharacteristics.getPhysicalCameraIds();
if(physicalCameraIdS.size()>=2)
{
Log.i(" Message : ", "We have more then One camera");
}
else{
Log.i(" Message : ", "We Do not have multip[le cameras");
}
}
}
catch (CameraAccessException e)
{
Log.i("Camera Error", e.toString());
}
}
else
{
requestPermissions(new String[]{Manifest.permission.CAMERA},1);
}
}
Manifest permissions
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.front" />
<uses-feature android:name="android.hardware.camera.back" />```
Can someone explain what I'm doing wrong, and how to do it properly?
I'm answering this questions in order to prevent other people from making my mistake. As I stated in my question, I'm trying to run that code on an Xiaomi Redmi Note 9 and digging internet a little more I found out that Redmi Note 9S and 9Pro support the Android 11(API 30) while regular Redmi Note 9 doesn't yet. It runs on Android 10 (API 29) while the code that I wrote is for API 30 so only thing that I have to is just wait till an update to Android 11 for Redmi Note 9.
Thanks for people that looked at this question and I consider the question answered.

Android NDK C++ camera2 API: ACameraManager_getCameraIdList return 0 cameras

I'm trying to create C++ Android native camera wrapper using the NDK camera2 API (from abi level 24). I created some snippet code using an example I found and compile it for target API level 24 and run it on Android 7.1 phone:
ACameraManager *cameraManager = ACameraManager_create();
VB(cameraManager!=nullptr, "Could not create CameraManager.");
camera_status = ACameraManager_getCameraIdList(cameraManager, &m_camera_id_list);
if (camera_status != ACAMERA_OK) {
LOGE("Failed to get camera id list (reason: %d)\n", camera_status);
return ERR_CAMERAAPI_UNKNOWN_ERROR;
}
if (m_camera_id_list->numCameras < 1) {
LOGE("No camera device detected.\n");
return ERR_CAMERAAPI_UNKNOWN_ERROR;
}
When I run this naive code on Xiaomi mi4c Android 7.1 phone I get an empty camera list.
I also tried to run on the same phone a snippet created with Java camera2 API that does the same thing:
import android.hardware.camera2.CameraDevice;
Activity activity = getActivity();
CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
String[] cameraIds = manager.getCameraIdList()
manager.openCamera(cameraIds[0], mStateCallback, mBackgroundHandler);
This time I see in the logical that it actually finds two cameras and print their resolutions.
My manifest of course contains these lines:
<uses-sdk android:minSdkVersion="24" />
<uses-feature android:name="android.hardware.camera2" android:required="true" />
<uses-feature android:name="android.hardware.sensor.gyroscope" android:required="false" />
<uses-permission android:name="android.permission.CAMERA"/>
And I approve the permissions requests.
Does anyone knows why it finds the phone cameras when using the Java camera2 API but does not find them when using the NDK camera2 API?
The NDK camera2 support does not work if
CameraCharacteristics.get(INFO_SUPPORTED_HARDWARE_LEVEL) == INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY
This is probably the case of Xiaomi mi4c.

Reasons why Android camera unavailable

I using android android.hardware.Camera class to capture image. For initialization I use following code.
Camera cam = null;
try {
cam = Camera.open();
} catch (Exception e) {
e.printStackTrace();
// camera unavailable
}
return cam;
I am interesting in catch block. For example, torch app is running at the moment of initialization. So Camera.open() throw RuntimeException with message Fail to connect to camera service.
Here is exception:
Is it possible to know the reason why camera is unavailable? I want to guide user how to fix this, for example show a dialog: "dude, turn off your torch".
If it's not possible, then in which cases camera could be blocked? I just will show user dialog with general instruction what he could do, for example: 1. turn off torch. 2. Close all camera app 3. Fed your cat etc.

Activating screen cast by Intent

Is there an Intent that will activate the screen mirror function of the Google Cast App?
I require the use of this function, and I would like to make its activation as streamlined as possible.
No, the user has to activate the feature. If you want to mirror your own apps content to a Cast device, then use the Google Cast Remote Display API.
If you are interested in developing a Remote Display app for screen mirroring, there is a library, castscreen, which reduces the process to a few lines of code.
Unfortunately, there's no way to make the process as streamlined as the Google Cast app: they use the READ_FRAME_BUFFER manifest permission to get the user's screen contents, whereas third-party apps have to explicitly ask the user for screen capture permission (for clear security reasons). You can use READ_FRAME_BUFFER if you ship your own ROM signed with the same private key as the application, though that is impractical for most use cases.
this is a simple method for implementing mirror casting (not google casting).
try {
startActivity(new Intent("android.settings.WIFI_DISPLAY_SETTINGS"));
} catch (ActivityNotFoundException e) {
e.printStackTrace();
try {
startActivity(new Intent("com.samsung.wfd.LAUNCH_WFD_PICKER_DLG"));
} catch (Exception e2) {
try {
startActivity(new Intent("android.settings.CAST_SETTINGS"));
} catch (Exception e3) {
Toast.makeText(getApplicationContext(), "Device not supported", Toast.LENGTH_LONG).show();
}
}
}
with these permissions :
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

android java lang runtimeexception fail to connect to camera service

I am currently working on Flashlight On/OFF. I am getting this error java.lang.RuntimeException: Fail to connect to camera service I don't know why this error is occurring. I referred to many solutions but my problem was still not solved. When flashlight is on, the error does not occur but when the flashlight is off then the error occurs.
My Code Main Code.
My Manifest permission:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus"/>
I had the same issue that none of the answers here solved, so after solving it I am adding my way of solving it. This applies to new android versions that support setting permissions per app (since Marshmallow, 6.0). The permission for camera could be disabled and should be enabled from the app settings.
Settings -> Apps -> [Your App] -> Permissions
More info about this here: http://developer.android.com/training/permissions/requesting.html
I also saw this error:
java.lang.RuntimeException: Fail to connect to camera service
while experimenting with a flashlight app. Turns out that I was a bit sloppy with my permissions and copied them into the body of the application block in the manifest.xml file. So you REALLY need to obey the syntax as documented in:
http://developer.android.com/guide/topics/manifest/manifest-element.html
Otherwise the app will fail with service connection failure on the Camera.open() call. It should look like this based on your permissions in the question:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus"/>
<application
Make sure your permission and feature list is contained only in the manifest section, and not buried in the application section!
try this...
static Camera camera = null;
declare it on top.
try{
if(clickOn == true) {
clickOn = false;
camera = Camera.open();
Parameters parameters = camera.getParameters();
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
remoteViews.setViewVisibility(R.id.button1, View.GONE);
remoteViews.setViewVisibility(R.id.button2, View.VISIBLE);
localAppWidgetManager.updateAppWidget(componentName, remoteViews);
} else {
clickOn = true;
camera.stopPreview();
camera.release();
camera = null;
remoteViews.setViewVisibility(R.id.button1, View.VISIBLE);
remoteViews.setViewVisibility(R.id.button2, View.GONE);
localAppWidgetManager.updateAppWidget(componentName, remoteViews);
}
} catch(Exception e) {
Log.e("Error", ""+e);
}
This problem may arise in android 6.0 if you didn't enable camera permission for your app. As from Android 6.0 you can handle the app permission weather you will give or not specific permission for an application.
So, you need to enable permission from settings->apps->your_app->enable camera permission if its not already enabled.
If your os version is 6.0 or later version try this, hope this will help.
public class RequestUserPermission {
private Activity activity;
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
};
public RequestUserPermission(Activity activity) {
this.activity = activity;
}
public void verifyStoragePermissions() {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
}
**//CALL FROM YOUR ACTIVITY**
RequestUserPermission requestUserPermission = new RequestUserPermission(this);
requestUserPermission.verifyStoragePermissions();
if you try to open the camera using a cameraID that does not exist, you will receive that same error (java.lang.RuntimeException: Fail to Connect to camera service)
look at your code at this block
camera.setParameters(parameters);
camera.stopPreview();
camera.release();
camera = null;
Call release() to release the camera for use by other applications. Applications should release the camera immediately in onPause() (and re-open() it in onResume().
In above code imediately after release you are putting null to camera
Hi i hope you are dealing with a torch kind of app or something related to flash and there were many discussions went on this before and here are some useful links and tutorials to achieve your need, please go through them hope they may help you
How to turn on camera flash light programmatically in Android?
http://www.androidhive.info/2013/04/android-developing-flashlight-application/
http://www.compiletimeerror.com/2013/08/how-to-turn-onoff-camera-led-flashlight.html#.U4WH5Xbc3o4
http://android.programmerguru.com/android-flashlight-example/
You need to stopPreview() and release() once you came back from camera,
so that other application can able to access it. Make the "Camera" class as static and refer it as null in onPause(). This resolves my Issue.
Try it out:
public class CameraPhotoCapture extends Activity{
static Camera mcamera = null;
#Override
protected void onPause() {
// TODO Auto-generated method stub
if (mcamera != null) {
mcamera.stopPreview();
mcamera.release();
mcamera = null;
Log.d(DEBUG_TAG, "releaseCamera -- done");
}
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
if (mcamera != null) {
Camera.open();
Log.d(DEBUG_TAG, "openCamera -- done");
}
super.onResume();
}
}
The simple answer I can find to this problem is I was not asking for camera permission to the user, and that's why by default camera permission was not available to my app on Marshmallow devices. I simply added permission check for the camera before starting the camera and everything works fine.
private boolean checkPermission() {
if (ContextCompat.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
return true;
}
return false;
}
Check the camera permission at runtime, and request the permission if it has not be granted. It works for me.
if (checkPermission()) {
initCamera();
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
}
Try to use this line, when you're exiting the app :
System.exit(0);
I just got a code of an Flashlight app from somewhere. It was using System.exit(0) to close the app. I removed it, knowing that this is not a good practice. Then I started to receive these errors. I tried the solution of the accepted answer, but then I started receiving some other errors. So, instead of solving them I just put this System.exit(0) line back. And, it started working fine. I know this is not a good way, but for a small flashlight app, you can try this quick solution.
Set the Required permission in Mainfest file.
Ask the Permission to accept the Camera.
It will work for me
If all your code is ok, you should check are there any other application using your camera. Then you should close other application that currently using your camera.
In my android peoject has the same issue. This is my Logcat error
03-29 19:26:04.194 224-608/? V/EmulatedCamera_BaseCamera:
getCameraInfo 03-29 19:26:04.196 224-224/? I/CameraService:
CameraService::connect call (PID -1 "com.proitzen.staffapp", camera ID
1) for HAL version default and Camera API version 1 03-29 19:26:04.196
224-224/? W/ServiceManager: Permission failure:
android.permission.CAMERA from uid=10067 pid=1776 03-29 19:26:04.196
224-224/? E/CameraService: Permission Denial: can't use the camera
pid=1776, uid=10067 03-29 19:26:04.196 1776-1776/com.proitzen.staffapp
W/CameraBase: An error occurred while connecting to camera 1: Service
not available 03-29 19:26:04.200 1776-1776/com.proitzen.staffapp
D/AndroidRuntime: Shutting down VM
No any above solutions worked for me. My android app worked in physical android devices and gave the above error only in Genymotion.
Solution : start your Genumotion emulator
Settings --> Apps ---> choose your App --> Permissions --> enable camera and Mic and storage.

Categories

Resources