I want to write a flashlight. The result was such a code, but for some reason it did not work on Android 5.1 it checked on the Galaxy Grand Prime phone.

public class MainActivity extends AppCompatActivity { private ImageButton btnSwitch = null; private Camera camera = null; private boolean isFlashOn; //булева переменная для определения включен ли фонарик private boolean hasFlash; //переменная для определения есть ли вообще фонарик private Camera.Parameters params; private CameraManager mCameraManager; private String mCameraId; private MediaPlayer mp; private RelativeLayout activity_main; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); activity_main = (RelativeLayout) findViewById(R.id.activity_main); btnSwitch = (ImageButton) findViewById(R.id.btnOnOff); isFlashOn = false; //найти камеру hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH); if (!hasFlash) { errorDialog(); } getCamera(); btnSwitch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isFlashOn) { turnOff(); } else { turnOn(); } } }); } //Получаем камеру устройства public void getCamera() { if (Build.VERSION.SDK_INT >= 21) { mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); try { mCameraId = mCameraManager.getCameraIdList()[0]; } catch (Exception ex) { ex.printStackTrace(); } } else { if (camera == null) { try { camera = Camera.open(); camera.getParameters(); } catch (RuntimeException ex) { ex.printStackTrace(); } } } } public void turnOff() { if (isFlashOn) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { try { mCameraManager.setTorchMode(mCameraId, false); isFlashOn = false; playOnOffSound(); btnSwitch.setImageResource(R.drawable.button_off); activity_main.setBackgroundResource(R.drawable.bg_off); } catch (Exception ex) { ex.printStackTrace(); } } else { if (camera == null || params == null) { return; } params = camera.getParameters(); params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); camera.setParameters(params); camera.stopPreview(); isFlashOn = false; playOnOffSound(); btnSwitch.setImageResource(R.drawable.button_off); activity_main.setBackgroundResource(R.drawable.bg_off); } } } public void turnOn() { if (!isFlashOn) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { try { mCameraManager.setTorchMode(mCameraId, true); playOnOffSound(); isFlashOn = true; btnSwitch.setImageResource(R.drawable.button_on); activity_main.setBackgroundResource(R.drawable.bg_on); } catch (Exception ex) { ex.printStackTrace(); } } else { if (camera == null || params == null) { return; } params = camera.getParameters(); params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); camera.setParameters(params); camera.startPreview(); playOnOffSound(); btnSwitch.setImageResource(R.drawable.button_on); activity_main.setBackgroundResource(R.drawable.bg_on); isFlashOn = true; } } } private void playOnOffSound(){ mp = MediaPlayer.create(this, R.raw.flash_sound); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); mp.start(); } @Override protected void onStop() { super.onStop(); if(isFlashOn){ turnOff(); } } @Override protected void onPause() { super.onPause(); if(isFlashOn){ turnOff(); } } @Override protected void onResume() { super.onResume(); if(isFlashOn){ turnOn(); } } public void errorDialog() { //создаем диалоговое окно AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).create(); dialog.setTitle("Ошибка!"); dialog.setMessage("Ваше устройство не поддерживает работу со вспышкой."); dialog.setButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }); dialog.show(); return; } } 

In the manifesto prescribed the following

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

As I understand it does not work due to conditions

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 

but if I register this condition instead

 if (Build.VERSION.SDK_INT >= 21) 

then swears in this place

 mCameraManager.setTorchMode(mCameraId, false); 

Call requires API level 23 (current min is 14): android.hardware.camera2.CameraManager # setTorchMode less ... (Ctrl + F1)

Android 6 is fine

    1 answer 1

    The CameraManager.setTorchMode() method is available starting from API 23, therefore it is “swearing”. Reducing the API in the condition is not necessary - for smaller APIs you have a branch with an alternative inclusion.

    The problem is that not all devices correctly handle the Camera.Parameters.FLASH_MODE_TORCH attribute, so the flashlight does not turn on.

    In particular, this behavior is known Samsung products and for their products have to come up with crutches, there are also some special models. For them you need to look for individual solutions.

    UPDATE
    Great question on this issue on enSO. Universal solution for API <23, as I understand it, no.

    • hmm weird .. We will search then. Thank. - Victoria
    • Something did not find normal solutions how to make the flashlight work on android 5. Can someone give a link to the source? - Victoria
    • Thanks, I will understand now. - Victoria