I want to create an Android application using Java that displays the toast message when the user turns on or off the flashlight from the system and not from the app. I discovered that there is no built-in broadcaster to receive this information and I have to create the custom broadcast receiver for this. Please someone help with the logic to build the custom broadcast receiver for the state of the flashlight.
package com.example.lab7_torch;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.widget.Toast;
public class TorchChangeReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent){
if(intent != null && intent.getAction() != null){
if(intent.getAction().equals("android.hardware.action.Action_Torch_On")) {
boolean isTorchOn = intent.getBooleanExtra("torch_state", false);
if (isTorchOn){
Toast.makeText(context,"Torch is On", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context,"Torch is Off", Toast.LENGTH_SHORT).show();
}
}
}
}
I tried this code for a custom broadcast receiver but it is not working.
I don't think there is any broadcast receiver to register for tracking flashlight/torch status. Where do you get this
android.hardware.action.Action_Torch_Onfrom?You would need to utilize the camera manager to track the status of the flashlight/torch.
ref: https://developer.android.com/reference/android/hardware/camera2/CameraManager
you must also add Camera and Flashlight permissions to access the status.