I am trying to turn my phone's torch on and off, in the main activity the following works and turns the torch on, it needs an API of 21 or more, all good.
class MainActivity : AppCompatActivity() {
private lateinit var cameraManager : CameraManager
private lateinit var cameraID : String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Populate the default preference values from the XML, kind of neat
PreferenceManager.setDefaultValues(this, R.xml.app_preferences, true)
setContentView(R.layout.activity_main)
setSupportActionBar(findViewById(R.id.toolbar))
cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
cameraID = cameraManager.cameraIdList[0]
cameraManager.setTorchMode(cameraID, true)
}
However, I am trying to use the recommended architecture of an application with one activity and multiple fragments, so one of my fragments shows an on/off button and I want to control the torch from there.
So …
class ButtonsFragment : Fragment() {
private lateinit var cameraManager : CameraManager
……...
private fun syncTorch() {
// Sync the display to the correct ic (ic - icon)
if (torch.currentState) {
onButton.setBackgroundResource(R.drawable.ic_led_circle_green)
cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
val cameraID = cameraManager.cameraIdList[0] as String
cameraManager.setTorchMode(cameraID, true)
} else {
onButton.setBackgroundResource(R.drawable.ic_led_circle_grey)
}
}
First issue is that the min API has to be upgraded to API 23 ? Why does it need a higher API just because I moved the code into a Fragment ?
Also I had to add context. before .getSystemService(Context.CAMERA_SERVICE) as CameraManager, assuming this is implied in the main activity ?
Lastly I get an error around the . in cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager, saying only safe or non asserted calls allowed on nullable receiver Context where I did not have this error when it was in the activity, any ideas ?
I seem to be running into a lot of issues using this code in a fragment. Any help to clarify this greatly appreciated.