'Which permissions are required for Flashlight?

I've used <uses-permission android:name="android.permission.FLASHLIGHT" /> but my app keeps crashing. I'm making a Torch app. Here's my Manifest code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.Torch">
    <uses-permission android:name="android.permission.FLASHLIGHT" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name="com.Torch.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Error log:

03-28 15:29:23.439 7163-7163/com.Torch E/AndroidRuntime: FATAL EXCEPTION: main
 Process: com.Torch, PID: 7163
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Torch/com.Torch.MainActivity}: java.lang.RuntimeException: Fail to connect to camera service
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2493)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2555)
     at android.app.ActivityThread.access$800(ActivityThread.java:176)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1437)
     at android.os.Handler.dispatchMessage(Handler.java:111)
     at android.os.Looper.loop(Looper.java:194)
     at android.app.ActivityThread.main(ActivityThread.java:5576)
     at java.lang.reflect.Method.invoke(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:372)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
  Caused by: java.lang.RuntimeException: Fail to connect to camera service
     at android.hardware.Camera.<init>(Camera.java:637)
     at android.hardware.Camera.open(Camera.java:496)
     at com.Torch.MainActivity.onCreate(MainActivity.java:33)
     at android.app.Activity.performCreate(Activity.java:6005)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2446)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2555) 
     at android.app.ActivityThread.access$800(ActivityThread.java:176) 
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1437) 
     at android.os.Handler.dispatchMessage(Handler.java:111) 
     at android.os.Looper.loop(Looper.java:194) 
     at android.app.ActivityThread.main(ActivityThread.java:5576) 
     at java.lang.reflect.Method.invoke(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:372) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751) 


Solution 1:[1]

add in your manifest

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

and for android M devices be sure to ask permission

 if((ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.FLASHLIGHT)  != PackageManager.PERMISSION_GRANTED) || 
                   (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)  != PackageManager.PERMISSION_GRANTED)){
           requestPermissions(new String[]{Manifest.permission.FLASHLIGHT, Manifest.permission.CAMERA});
 }
 else{

 }



@Override
public void onRequestPermissionsResult(int requestCode, String[]     permissions, int[] grantResults) {

    boolean canUseCamera = false;
    boolean canUseFlash = false;

    switch (requestCode) {
        case PERMISSION_CODE_CAMERA: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                canUseCamera  = true;
            }
            if (grantResults.length > 1
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                canUseFlash = true;
            }

            if (!canUseCamera || !canUseFlash ) {
                Toast.makeText(getActivity(), "Cannot use this feature without requested permission", Toast.LENGTH_SHORT).show();
            } else {
                // do your actual task
            }
        }
    }
}

Solution 2:[2]

Add Camera Permission only... with api 22

Solution 3:[3]

I've made a sample to toggle the flashlight of the front facing camera/s. Hope you will find it useful:

manifest:

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

MainActivity.kt

class MainActivity : AppCompatActivity() {
    private val cameraIdsToToggle = HashSet<String>()
    private var turnTorchOn: Boolean? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val camManager: CameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
        val callback = object : CameraManager.TorchCallback() {
            override fun onTorchModeChanged(cameraId: String, enabled: Boolean) {
                super.onTorchModeChanged(cameraId, enabled)
                Log.d("AppLog", "onTorchModeChanged cameraId:$cameraId enabled:$enabled")
                if (cameraIdsToToggle.remove(cameraId)) {
                    var needToTurnOn = turnTorchOn
                    if (needToTurnOn == null) {
                        needToTurnOn = !enabled
                        turnTorchOn = needToTurnOn
                    }
                    if (needToTurnOn != enabled) {
                        Log.d("AppLog", "turning camera flash of $cameraId from $enabled to:$needToTurnOn")
                        camManager.setTorchMode(cameraId, needToTurnOn)
                    }
                }
                if (cameraIdsToToggle.isEmpty())
                    camManager.unregisterTorchCallback(this)
            }
        }
        Log.d("AppLog", "camera list:")
        camManager.cameraIdList.forEach { cameraId ->
            val cameraCharacteristics: CameraCharacteristics = camManager.getCameraCharacteristics(cameraId)
            if (cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE) == true
                && cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == CameraMetadata.LENS_FACING_BACK
            ) {
                Log.d("AppLog", "found back camera with flash $cameraId")
                cameraIdsToToggle.add(cameraId)
            }
        }
        camManager.registerTorchCallback(callback, null)
        finish()
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Saud Kamran
Solution 3 android developer