cannot open camera "0" without camera permission - java

I have the following in my manifest
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.CAMERA" />
however I receive this error
An error occurred while connecting to camera 0: Status(-8, EX_SERVICE_SPECIFIC): '1: validateClientPermissionsLocked:1165: Caller ... (PID 10153, UID 6049) cannot open camera "0" without camera permission'
I am attempting to get a camera working using this code
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open();
} catch (Exception e) {
Log.e("getCameraInstance", "exception", e);
}
return c; // returns null if camera is unavailable
}
How do I get this camera working?

Need to enable permissions at runtime. The above error is outputted when the 0 indexed camera does not have permissions. Adding permissions to the manifest is not what enables it on the phone... the below code will.
public static void checkCameraPermissions(Context context){
if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED)
{
// Permission is not granted
Log.d("checkCameraPermissions", "No Camera Permissions");
ActivityCompat.requestPermissions((Activity) context,
new String[] { Manifest.permission.CAMERA },
100);
}
}

Related

Huawei Honor 10 blocked Bluetooth when app is running

I`m development network radio app for Android API 21-29 and all worked fine but one cases confuses me. On Huawei Honor 10 when my app started playing and trying to switch on the Bluetooth nothing works. Device turn-off Bluetooth and all. I add this permission in my AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
If Bluetooth turn on before playing, he turn off right after start play.
I used this method when app send mediasession.OnPlay
#Override
public void onPlay() {
if (!exoPlayer.getPlayWhenReady()) {
startService(new Intent(getApplicationContext(), PlayerService.class));
if (stationsRepository == null)
return;
station = stationsRepository.getCurrent();
bitrate = Connectivity.currentBitrate;
String stream = station.getStreamByBitrate(bitrate);
prepareToPlay(Uri.parse(stream));
mediaSession.setQueueTitle(station.getTitle());
if (!audioFocusRequested) {
audioFocusRequested = true;
int audioFocusResult;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
audioFocusResult = audioManager.requestAudioFocus(audioFocusRequest);
} else {
audioFocusResult = audioManager.requestAudioFocus(audioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
}
if (audioFocusResult != AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
return;
}
mediaSession.setActive(true);
registerReceiver(becomingNoisyReceiver, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));
exoPlayer.setPlayWhenReady(true);
}
mediaSession.setPlaybackState(stateBuilder.setState(PlaybackStateCompat.STATE_PLAYING, PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1).build());
currentState = PlaybackStateCompat.STATE_PLAYING;
refreshNotificationAndForegroundStatus(currentState);
}
On same devices uses Android 10, Android 8, Android 7 all work is fine.
Can anyone help me fix with this.
P.S. Sorry for my English. This is the first time when I ask a question in this language.
Update: Tested on Huawei P30 lite and catch this bug too.

Android Studio Java Bluetooth LE doesn't work

So I have my Arduino advertising BLE, I can download, "BLE Scanner" app to connect to it and it works that way. Now I'm writing app on Android to connect to that Arduino. I've got following code but it doesn't work:
ScanCallback scanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, final ScanResult result) {
super.onScanResult(callbackType, result);
System.out.println("Callback: " + callbackType);
}
#Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
System.out.println("callback error");
}
};
BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
BluetoothLeScanner mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
ScanSettings scanSettings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
mLEScanner.startScan(null,scanSettings,scanCallback);
and I'm getting this error:
I/BNRClientProivder, VERSION : 1.7.5: register - xml6 quick_backup : ACCESSIBILITYSETTINGS, X6qErjsfs2, com.android.settings.accessibility.sharedaccessibility.scloud.BNRTask
I/QBNRClientHelper: init SyncClientHelper : ACCESSIBILITYSETTINGS
I/BNRClientProivder, VERSION : 1.7.5: register - xml6 quick_backup : CONNECTIONS, C0phMaUuZZ, com.android.settings.wifi.mobileap.WifiApBackupRestore
I/QBNRClientHelper: init SyncClientHelper : CONNECTIONS
I/BNRClientProivder, VERSION : 1.7.5: register - xml6 quick_backup : WiFi, C0phMaUuZZ, com.android.settings.wifi.WifiBackupRestore
Accessibility settings seems like permissions. You need to allow for ble features within the application.
Go to your manifest file add bluetooth permissions and location permissions
Then you will need to grant the app permissions when you run it. Go to your open apps and press the 3 dots, app info, permissions location enable.
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Also I cant see what the scan result it. On a ble scan callback you get the device address, scan record(advert data) and the rssi(power received).

How to turn on location in order to display found bluetooth device

I am trying to do a indoor location services using bluetooth LE scan to search for beacons. However, in order to display found bluetooth devices, location need to be turned on.
I tried searching online for solutions but to no avail. I have only enable the permission for the app not to turn on the location.
this is the code for the permission
if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("This app needs location access");
builder.setMessage("Please grant location access so this app can detect peripherals.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
}
});
builder.show();
}
i have also added the permission in android manifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Oreo problem in creating a directory onto the external storage

I try to create folder in android external storage. I try many example but it all isn't worked. I set run-time permissions for reading and writing to external storage. It is work on Android API 6, 7. but not work on Android Oreo.
File f = new File(Environment.getExternalStorageDirectory(), "MyDir");
if (!f.exists()) {
try {
boolean is_seccess = f.mkdirs();
if (is_seccess) {
Toast.makeText(this, "create", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "not create", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
e.printStackTrace();
}
}
I Checked if external storage is available for read and write, it return true.
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
I give below permissions, I also give run-time permission and allow it.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Just Android Oreo isn't work other device is working perfect. What is problem in my code?
The app requests READ_EXTERNAL_STORAGE and the user grants it. If the app targets API level 25 or lower, the system also grants WRITE_EXTERNAL_STORAGE at the same time, because it belongs to the same STORAGE permission group and is also registered in the manifest. If the app targets Android 8.0 (API level 26), the system grants only READ_EXTERNAL_STORAGE at that time; however, if the app later requests WRITE_EXTERNAL_STORAGE
Ask run time permission like below:
private boolean checkAndRequestPermissions() {
int permissionReadStorage = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
int permissionCamera = ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA);
int permissionWriteStorage = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
List<String> listPermissionsNeeded = new ArrayList<>();
if (permissionCamera != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.CAMERA);
}
if (permissionReadStorage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (permissionWriteStorage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions((Activity) this,
listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}

Camera app on android

I am beginner in android developing and I am trying to make a camera app. The camera app is opening but camera hardware is not detecting this is the code of main activity code. Now what am I missing to added to detect camera hardware please describe it and help me to solve it
public class CamTestActivity extends Activity {
private static final String TAG = "CamTestActivity";
Preview preview;
Button buttonClick;
Camera camera;
Activity act;
Context ctx;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = this;
act = this;
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
preview = new Preview(this, (SurfaceView)findViewById(R.id.surfaceView));
preview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
((FrameLayout) findViewById(R.id.layout)).addView(preview);
preview.setKeepScreenOn(true);
preview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
Toast.makeText(ctx, getString(R.string.take_photo_help), Toast.LENGTH_LONG).show();
buttonClick = (Button) findViewById(R.id.btnCapture);
buttonClick.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
preview.mCamera.takePicture(shutterCallback, rawCallback, jpegCallback);
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}catch (Exception e)
{
Toast.makeText(ctx, getString(R.string.camera_not_found), Toast.LENGTH_LONG).show();
}
}
});
buttonClick.setOnLongClickListener(new OnLongClickListener(){
#Override
public boolean onLongClick(View arg0) {
camera.autoFocus(new Camera.AutoFocusCallback(){
#Override
public void onAutoFocus(boolean arg0, Camera arg1) {
//camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
return true;
}
});
}
#Override
protected void onResume() {
super.onResume();
int numCams = Camera.getNumberOfCameras();
if(numCams > 0){
try{
camera = Camera.open(1);
camera.startPreview();
preview.setCamera(camera);
} catch (RuntimeException ex){
Toast.makeText(ctx, getString(R.string.camera_not_found), Toast.LENGTH_LONG).show();
}
}
}
#Override
protected void onPause() {
if(camera != null) {
camera.stopPreview();
preview.setCamera(null);
camera.release();
camera = null;
}
super.onPause();
}
private void resetCam() {
camera.startPreview();
preview.setCamera(camera);
}
private void refreshGallery(File file) {
Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(file));
sendBroadcast(mediaScanIntent);
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
// Log.d(TAG, "onShutter'd");
}
};
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// Log.d(TAG, "onPictureTaken - raw");
}
};
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
new SaveImageTask().execute(data);
resetCam();
Log.d(TAG, "onPictureTaken - jpeg");
}
};
private class SaveImageTask extends AsyncTask<byte[], Void, Void> {
#Override
protected Void doInBackground(byte[]... data) {
FileOutputStream outStream = null;
// Write to SD Card
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/camtest");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
outStream.write(data[0]);
outStream.flush();
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
refreshGallery(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return null;
}
}
}
this is the manifest code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.niit.cameraapp">
<uses-sdk android:minSdkVersion="9" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".CamTestActivity"
android:screenOrientation="portrait" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
this is the logcat error
04-26 12:20:13.694 9167-9167/com.example.niit.cameraapp I/zygote64: Late-enabling -Xcheck:jni
04-26 12:20:13.969 9167-9167/com.example.niit.cameraapp I/InstantRun: starting instant run server: is main process
04-26 12:20:14.142 9167-9167/com.example.niit.cameraapp W/.niit.cameraapp: type=1400 audit(0.0:84362): avc: denied { read } for name="u:object_r:camera_prop:s0" dev="tmpfs" ino=6271 scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:object_r:camera_prop:s0 tclass=file permissive=0
04-26 12:20:14.149 9167-9167/com.example.niit.cameraapp E/libc: Access denied finding property "camera.hal1.packagelist"
04-26 12:20:14.152 9167-9167/com.example.niit.cameraapp W/CameraBase: An error occurred while connecting to camera 1: Status(-8): '1: validateClientPermissionsLocked:920: Caller "com.example.niit.cameraapp" (PID 10190, UID 9167) cannot open camera "1" without camera permission'
04-26 12:20:14.181 9167-9330/com.example.niit.cameraapp D/OpenGLRenderer: HWUI GL Pipeline
04-26 12:20:14.233 9167-9330/com.example.niit.cameraapp I/Adreno: QUALCOMM build : 7f08991, I8a9bdcf8d3
04-26 12:20:14.236 9167-9330/com.example.niit.cameraapp I/vndksupport: sphal namespace is not configured for this process. Loading /vendor/lib64/hw/gralloc.msm8953.so from the current namespace instead.
04-26 12:20:14.232 9167-9167/com.example.niit.cameraapp W/RenderThread: type=1400 audit(0.0:84363): avc: denied { search } for name="proc" dev="debugfs" ino=5174 scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:object_r:qti_debugfs:s0 tclass=dir permissive=0
04-26 12:20:14.244 9167-9330/com.example.niit.cameraapp I/Adreno: PFP: 0x005ff087, ME: 0x005ff063
04-26 12:20:14.249 9167-9330/com.example.niit.cameraapp I/OpenGLRenderer: Initialized EGL, version 1.4
04-26 12:20:14.249 9167-9330/com.example.niit.cameraapp D/OpenGLRenderer: Swap behavior 2
04-26 12:20:14.309 9167-9330/com.example.niit.cameraapp I/vndksupport: sphal namespace is not configured for this process. Loading /vendor/lib64/hw/gralloc.msm8953.so from the current namespace instead.
04-26 12:20:17.316 9167-9202/com.example.niit.cameraapp I/zygote64: Debugger is no longer active
screenshot of the deployed app
The issue is most likely that, while you have asked for the Camera permission in the manifest, you also need to ask at runtime. The reason is that in older versions of Android (I think < Android 6.0), you only needed to declare permissions in the manifest. However, now the user can turn permissions on and off after the app has been installed. So now you are supposed to check during runtime whether you have permission for the feature you require. If you don't have it, then you should ask the user to enable it.
You can find code for this online. But first we need to verify that that is indeed the problem. The simplest way of doing that is by going to your Android Settings app. Then in there, there should be an Apps options. Find your app and click on it. In there, there should be a section with the Permissions. If the camera permission is not checked there, then check it and rerun your app.
If this fixes your issue, then you need to find code to ask the user to grant you the permission after the app opens. One such way of doing this is simply on the splash screen, as demonstrated here.
I assume you are running the app on a device with Android 6 or higher. So, you should additionally check for the runtime permissions to use the camera:
https://developer.android.com/training/permissions/requesting
If you don't add this permission check, Android will block the access to the camera hardware. It will also block hardware detection, because it requires also the camera permission. So, everytime you make a call on camera it will fail with a permission denied exception, which is logged in you logcat:
04-26 12:20:14.152 9167-9167/com.example.niit.cameraapp W/CameraBase: An error occurred while connecting to camera 1: Status(-8): '1: validateClientPermissionsLocked:920: Caller "com.example.niit.cameraapp" (PID 10190, UID 9167) cannot open camera "1" without camera permission'
Additionally, it seems you are using the deprecated camera api instead of the camera2 api:
https://developer.android.com/reference/android/hardware/camera2/package-summary

Categories

Resources