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;
}
}
}