I want to blink flashlight on incoming call. Everytime this code is going in service method i.e its running fine, its starting the service fine but the problem is its unable to start camera service everytime. If camera is running the blinking is not stopping if the call state changes. How could i start camera everytime and stop the blinking if the call state changes??
The code i used...
in manifest
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.FLASHLIGHT"/>
in service
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
try {
cam = Camera.open();
p = cam.getParameters();
String myString = "0101010101010101010101010101010101010101010101011";
long blinkDelay = 150;
cam.setParameters(p);
for (int i = 0; i < myString.length(); i++) {
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
break;
}else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
break;
}
if (myString.charAt(i) == '0') {
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
} else {
p.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(p);
}
try {
Thread.sleep(blinkDelay);
} catch (Exception e) {
Log.d(tag, e.toString());
p.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(p);
}
}
}catch (Exception e) {
// TODO: handle exception
Log.d(tag, "in catch1");
Log.d(tag, e.toString());
}
}else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
cam.release();
stopSelf();
}else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
cam.release();
stopSelf();
}
}
The logcat is not stopping and it is still running , crazy is the tag that i declared i got this
03-11 23:11:08.129: W/CameraService(133): CameraService::connect X (pid 942) rejected (existing client).
03-11 23:11:08.139: D/crazy(942): in catch1
03-11 23:11:08.139: D/crazy(942): java.lang.RuntimeException: Fail to connect to camera service
If you check out the Camera documentation, one reason that opening the camera could throw a RuntimeException is that another process is using the camera, which is what the error log seems to indicate. Check what other processes are running and make sure nothing else is using the camera (you should also be properly handling this error).
You should also make sure your application is calling release() on the camera, so that you aren't blocking other applications from using it.
Related
Problem happening on a Nokia 6 with Android 7.1.1
Permission granted
AppOpsManager#checkOp(AppOpsManager.OPSTR_CAMERA, Process.myUid(), getPackageName()) returns AppOpsManager#MODE_ALLOWED
Yet when trying Camera.open(i) for checking camera properties I get
I/CameraService: Camera 0: Access for "package" has been restricted
Apparently this could only happen [1] if application's package or uId has been explicitly restricted from starting AppOpsManager#OP_CAMERA.
But why would this happen? After AppOpsManager#checkOp says AppOpsManager#MODE_ALLOWED
Sample code
for (int i = 0; i < numCameras; ++i) {
List<Size> supportedSizes = null;
List<int[]> supportedFpsRanges = null;
Camera camera = null;
try {
camera = Camera.open(i);
Parameters parameters = camera.getParameters();
supportedSizes = parameters.getSupportedPreviewSizes();
supportedFpsRanges = getFpsRangesRobust(parameters);
} catch (Exception e) {
...
} finally {
if (camera != null) {
camera.release();
}
}
[1] https://github.com/aosp-mirror/platform_frameworks_base/blob/oreo-mr1-release/services/core/java/com/android/server/AppOpsService.java#L2588
Aparently it's a device issue.
Nokia 6 / TA-1000, Android 7.1.1
The scenario
try to use camera
app asks for permission, tap Deny
try to use camera
app asks for permission, tap Allow
Error posted in logcat, camera doesn't work
Is reproducible with any other application, including the default camera app.
Check you have added this line to your app manifest.
android:foregroundServiceType="camera"
Camera cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
The above dose not work on Lollipop, Because Camera is deprecated in Lollipop. I cant able to find any other way to turn on flash programmatically in Lollipop. How can I achieve this. Thanks in advance.
Camera class is now deprecated.
For LOLLIPOP above you need to use camera2 Api
so nickkadrov's solution doesent work for 6.0 & above device,best way to on/off flash light is try code below
public static void toggleFlashLight(){
toggle=!toggle;
try {
CameraManager cameraManager = (CameraManager) getApplicationContext().getSystemService(Context.CAMERA_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
for (String id : cameraManager.getCameraIdList()) {
// Turn on the flash if camera has one
if (cameraManager.getCameraCharacteristics(id).get(CameraCharacteristics.FLASH_INFO_AVAILABLE)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(id, true);
}
}
}
}
} catch (Exception e2) {
Toast.makeText(getApplicationContext(), "Torch Failed: " + e2.getMessage(), Toast.LENGTH_SHORT).show();
}
}
where toggle is class level static Boolean variable whose default value is false
static boolean toggle=false;
mCam = Camera.open();
Camera.Parameters p = mCam.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCam.setParameters(p);
mPreviewTexture = new SurfaceTexture(0);
try {
mCam.setPreviewTexture(mPreviewTexture);
} catch (IOException ex) {
// Ignore
}
mCam.startPreview();
It works for me on Android 5.0.x. And don't forget to add permission in manifest for camera usage.
<uses-permission android:name="android.permission.CAMERA" />
Your code should actually work. Please check if you added the permission for using the camera properly:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT"/>
This should be added to your AndroidManifest above of your other specifications.
Additionally, there is an interesting discussion about different devices and an example which should work on every device here: Flashlight in Android
If you dont want to use the deprecated API, you can check out:
Package Summary of Camera2
Camera device specification on the new api
Unfortunately I can not give you an example for using the new API, because I did not use it myself yet.
What I would do is simply turn on flash led of my phone by press a button. As I could read, it appear too much simple, but code I've found doesn't work!
This is how I turn on led at click on button: +
private void cameraOn() {
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
torch_button.setText("Switch off");
isTorchOn = true;
}
Params and camera object was initialized inside onCreate method. No error is thrown, but light doesn't switch on.
what's wrong?
Looks like this one has possibly already been answered
How to turn on camera flash light programmatically in Android?
But basically you need to have the correct permissions.
<!-- Allows access to the flashlight -->
<permission android:name="android.permission.FLASHLIGHT"
android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
android:protectionLevel="normal"
android:label="#string/permlab_flashlight"
android:description="#string/permdesc_flashlight" />
The problem could be another application holding the camera. Your code seems to be right.
I had done it successfully with this code :
Parameters p = null;
try {
p = camera.getParameters();
} catch (Exception e) {
e.printStackTrace();
}
if (isLightOn) {
Log.e("info", "turning off!");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLightOn = false;
} else {
Log.e("info", "turning on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLightOn = true;
}
Following is the code which I used for opening Torch and closing it. But when I close it, it crashes. LogCat says " Runtime Exception : Fail to connect to camera service "!
+
hasFlash is not getting any value and is throwing Nullpointer exception. (I'm using it to check if the flash is present or not.)
What am I doing Wrong?
boolean hasFlash = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(hasFlash==true)
{
if(s.equalsIgnoreCase("FlashLight On") || s.equalsIgnoreCase("Flash Light On"))
{
Camera cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
return "Turning on";
}
if(s.equalsIgnoreCase("FlashLight Off") || s.equalsIgnoreCase("Flash Light Off"))
{
Camera cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(p);
cam.stopPreview();
cam.release();
return "Turning off";
}
}
else
{
return "Flash Not Available";
}
Change
Camera cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(p);
cam.stopPreview();
cam.release();
return "Turning off";
to
cam.stopPreview();
cam.release();
return "Turning off";
I ran into a lot of these issues building an open source flashlight for Android which may help you with further questions.
Flashlight by Joe github
To check whether camera is running or not i am writing these code
ActivityManager actvityManager = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
String packageName = actvityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
if(packageName.equals("android.hardware.camera")||packageName.equals("com.android.camera")){
Camera_status = "STATUS_ON";
System.out.println("===on===");
}else{
Camera_status = "STATUS_OFF";
System.out.println("====off====");
}
By using this, i am able to get correct result in android emulator but while testing In real device i an not able to get the correct result.As per the answer posted here by CommonsWare,i think he is correct.So friends may i know how to get the camera on/off status programmatically.
Try This its working!!!
Camera _camera;
boolean qOpened = false;
try {
_camera=Camera.open();
qOpened=(_camera!=null);
if(qOpened){
Camera_status = "STATUS_OFF";
}else{
System.out.println("==nothing to do====");
}
} catch (Exception e) {
Camera_status = "STATUS_ON";
System.out.println("=====Camera running=====");
}