ShaSha
ShaSha

Reputation: 11

Camera.open() Why this line of code crashes my android app?

I am not a experienced programmer. I have just learnt some basic java and I was thinking about creating and android app. Actually a torch app. So I followed a youtube tutorial and wrote this code but it won't open in my phone. I have a Xiaomi android oreo version 8 phone.

Can anyone answer me please? Thanks in advance.

So this line makes my app crash camera = Camera.open();

It doesn't even open in my phone just shows a white screen then the app closes but it works fine in the Android studio emulator.

My code.

SDK versions:

android {
compileSdkVersion 28

    minSdkVersion 16
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

Manifest xml file;

<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<uses-feature android:name="android.hardware.camera"></uses-feature>
<uses-permission android:name="android.permission.FLASHLIGHT"></uses-permission>
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>

JAVA CODE:

public class MainActivity extends AppCompatActivity {

ImageButton imageButton;
Camera camera;
Camera.Parameters parameters;
boolean isFlash = false;
boolean isOn = false;

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

    imageButton = (ImageButton) findViewById(R.id.imageButton);

    if(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)){
        camera = Camera.open();
        parameters = camera.getParameters();
        isFlash = true;
    }

    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(isFlash == false){
                if(!isOn){
                    imageButton.setImageResource(R.drawable.on);
                    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                    camera.setParameters(parameters);
                    camera.startPreview();
                    isOn = true;
                }else {
                    imageButton.setImageResource(R.drawable.off);
                    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                    camera.setParameters(parameters);
                    camera.stopPreview();
                    isOn = false;
                }
            }else{
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Error...");
                builder.setMessage("flash is not available");
                builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                });
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
            }
        }
    });



    // end onCreate method
}

@Override
protected void onStop() {
    super.onStop();
    if(camera !=null){
        camera.release();
        camera = null;
    }
}
}

Upvotes: 0

Views: 846

Answers (1)

May Rest in Peace
May Rest in Peace

Reputation: 2207

Judging from your targetSDK (28) and your manifest permissions, I have a strong hunch that you haven't used runtime permissions.

Please add this to your code (which is basically invoking runtime permissions for camera) in place of camera opening logic :

if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
    if (ActivityCompat.shouldShowRequestPermissionRationale((Activity)
            getContext(), Manifest.permission.CAMERA)) {
    } else {
        ActivityCompat.requestPermissions((Activity) getContext(), 
                new String[]{Manifest.permission.CAMERA},
                42);
   }
}

42 is just a random number I chose which is supposed to be permission request code.

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 42:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_SHORT).show();

                camera = Camera.open();
                parameters = camera.getParameters();
                isFlash = true;
            } else {
                // failure logic
                }
            }
            break;
    }
}

onRequestPermissionsResult is the function that's called where you should handle your permission granted/rejected logic

Upvotes: 2

Related Questions