- Forum posts: 2
Jun 23, 2016, 9:04:17 PM via Website
Jun 23, 2016 9:04:17 PM via Website
Hi, i've recently picked up android developing and I know the basics, so I figured I could follow some tutorials and make a simple flashlight app. I tried coding the app in several ways but I could never manage to turn on the LED.
Here is the MainActivity
public class MainActivity extends AppCompatActivity {
ImageButton imageButton;
Camera camera;
Camera.Parameters parameters;
boolean isFlash = false;
boolean isOn = false;
@Override
protected void onStop() {
super.onStop();
if(camera != null){
camera.release();
camera = null;
}
}
@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) {
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 not supported");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
});
}
}
Recommended editorial content
With your consent, external content is loaded here.
By clicking on the button above, you agree that external content may be displayed to you. Personal data may be transmitted to third-party providers in the process. You can find more information about this in our Privacy Policy.