I'm trying to create simple Android application that simulate camera flashlight blink while phone call is received. If the user answer or cancel the call, I want to stop the flashlight blink. I'm using Handler and Runnable to simulate blinking, but the problem is that I can't stop the handler after user answer or cancel the call. My source code:
public class CallReceiver extends BroadcastReceiver
{
private static Camera cam = null;
private Handler handler = new Handler();
@Override
public void onReceive(Context context, Intent intent)
{
//device is ringing
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING))
{
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
{
startFlashBlink();
}
}
//call was answered or canceled
else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE)
|| intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK))
{
stopFlashBlink();
}
}
//for simulating flash blink
Runnable flashBlinkRunnable = new Runnable()
{
public void run()
{
cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
cam.stopPreview();
cam.release();
cam = null;
handler.post(flashBlinkRunnable);
}
};
//start flash blink light
public void startFlashBlink()
{
flashBlinkRunnable.run();
}
//stop flash blink light
public void stopFlashBlink()
{
handler.removeCallbacks(flashBlinkRunnable);
if (cam != null)
{
cam.stopPreview();
cam.release();
cam = null;
}
}
}