2

I've tried making a simple flashlight app but it either crashed or the LED never turns on. The problem seems to be asking for permissions but from the settings I can see the app already has it. Sorry coding is very hard. Here is the code

import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;

import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Switch;

public class MainActivity extends AppCompatActivity {

private boolean hasFlash;
private Camera camera;
Camera.Parameters params;
private boolean isFlashOn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



// SPERIMENTAL PERSMISSION ASKING COPIED FROM DEVELOPERS.ANDROID.COM
//(How the does it work)
    // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.CAMERA)) {

            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    500);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    }






    //set max brightness
    WindowManager.LayoutParams layout = getWindow().getAttributes();
    layout.screenBrightness = 1;
    getWindow().setAttributes(layout);


}

private void getCamera() {
    if (camera == null) {
        try {
            camera = Camera.open();
            params = camera.getParameters();
        } catch (RuntimeException e) {
            Log.e("Failed to Open. Error: ", e.getMessage());
        }
    }


}

public void onFlash() {
    if (!isFlashOn) {
        if (camera == null || params == null) {
            return;
        }

    }

    camera = Camera.open();
    camera.startPreview();
    params = camera.getParameters();
    params.setFlashMode(Parameters.FLASH_MODE_TORCH);
    camera.setParameters(params);

    isFlashOn = true;

}

public void offFlash() {
    if (!isFlashOn) {
        if (camera == null || params == null) {
            return;
        }

    }
    camera = Camera.open();
    params = camera.getParameters();
    params.setFlashMode(Parameters.FLASH_MODE_OFF);
    camera.setParameters(params);
    camera.stopPreview();
    isFlashOn = false;
}


public void toggleFlash() {
    if (isFlashOn) {
        offFlash();
    } else {
        onFlash();
    }
}




public void checkFlash(View v){
    hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    if(!hasFlash){
        //flash is not available
        //show a simple alert dialog
        AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
        alertDialog.setTitle("Error");
        alertDialog.setMessage("Couldn't connect to flash.");
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Ok",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alertDialog.show();
        //toggle the switch to its original position
        Switch lightButton = (Switch) findViewById(R.id.lightButton);
        lightButton.toggle();
    }else{
        toggleFlash();

    }

}



@Override
protected void onPause() {
    super.onPause();
}
@Override
protected void onDestroy(){
    super.onDestroy();
}
@Override
protected void onRestart(){
    super.onRestart();
}
@Override
protected void onResume(){
    super.onResume();
    getCamera();

}
@Override
protected void onStop(){
    super.onStop();
    camera.release();
}
@Override
protected void onStart(){
    super.onStart();

}

}

Stacktrace: (nothing important, the last lines appear when i hit the switch in the main screen)

06-22 01:01:18.736 32422-32422/com.andsp.brightledflashlight I/art: Late-enabling -Xcheck:jni
06-22 01:01:18.760 32422-32428/com.andsp.brightledflashlight E/art: Failed sending reply to debugger: Broken pipe
06-22 01:01:18.760 32422-32428/com.andsp.brightledflashlight I/art: Debugger is no longer active
06-22 01:01:18.775 32422-32422/com.andsp.brightledflashlight I/ActivityThread: Switching default density from 480 to 400
06-22 01:01:18.781 32422-32422/com.andsp.brightledflashlight W/System: ClassLoader referenced unknown path: /data/app/com.andsp.brightledflashlight-2/lib/arm
06-22 01:01:19.653 32422-32422/com.andsp.brightledflashlight W/System: ClassLoader referenced unknown path: /data/app/com.andsp.brightledflashlight-2/lib/arm
06-22 01:01:19.965 32422-32422/com.andsp.brightledflashlight W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
06-22 01:01:20.187 32422-32583/com.andsp.brightledflashlight D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
06-22 01:01:20.752 32422-32422/com.andsp.brightledflashlight I/Choreographer: Skipped 32 frames!  The application may be doing too much work on its main thread.
06-22 01:01:20.768 32422-32583/com.andsp.brightledflashlight I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: QUALCOMM Build: 10/21/15, 369a2ea, I96aee987eb
06-22 01:01:20.769 32422-32583/com.andsp.brightledflashlight I/OpenGLRenderer: Initialized EGL, version 1.4
**06-22 01:02:01.634 32422-32422/com.andsp.brightledflashlight E/Camera: Error 2
06-22 01:02:04.092 32422-32422/com.andsp.brightledflashlight E/Camera: Error 2
06-22 01:02:05.242 32422-32422/com.andsp.brightledflashlight E/Camera: Error 2**

activity_main.xml just in case

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.andsp.brightledflashlight.MainActivity">



    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/lightButton"
        android:layout_gravity="center"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:onClick="checkFlash"/>



</RelativeLayout>
Ddddddd
  • 55
  • 1
  • 9
  • Please include the stacktrace into your question. – Gennadii Saprykin Jun 21 '16 at 22:39
  • Sure, did that now. – Ddddddd Jun 21 '16 at 23:04
  • 1
    Your stacktrace does not have a crashlog. If your app really crashes it must have a stacktrace with a crashlog. – Gennadii Saprykin Jun 21 '16 at 23:06
  • You should narrow down your question as much as possible. Here is a link on how to use a flashlight on Android. Dig into that, try to do as much as you can, then come back and update your answer if you have any specific problem and not just "my app doesn't work". http://stackoverflow.com/questions/6068803/how-to-turn-on-camera-flash-light-programmatically-in-android – Gennadii Saprykin Jun 21 '16 at 23:28
  • Dude there is nothing more specific: i hit the switch, the only item in my layout. The LED does not turn on. I tried everything, but as of the codes i posted in OP the flash just doesnt work. Thanks dor the link though. – Ddddddd Jun 21 '16 at 23:31

2 Answers2

1

Since you're using Android Marshmallow (6.0), you can use the new Torch API which doesn't require camera permissions and makes the API more apparent and simpler for flashlight app developers.

Looking at your stacktrace, it seems like the Camera is reporting error code 2 which is CAMERA_ERROR_EVICTED. "Camera was disconnected due to use by higher priority user."

Maybe there's another app on your device which is using the camera. I'd take a look at the torch API first and then take a look at what other apps are using the camera.

Nick Felker
  • 11,536
  • 1
  • 21
  • 35
0

From your code, I can say that you still use the old camera api. If you've get the permission but flash not working, maybe because the device not working with the old api. Try use camera 2 api.

For simple working app with old camera api, you can learn from SimpleFlashLight.

For camera 2 look at Camera2

-- EDITED --

For working with range of api between api < 21 and api >= 21, you can use both of camera api (camera and camera2) by checking device build version like this:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
   //Use camera2
} else {
   //Use camera
}

The better option is to make your own api that interfaces both of the cameras api.

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96