我正在尝试创建简单的 Android 应用程序,以在接到电话时模拟相机手电筒闪烁。如果用户接听或取消通话,我想停止手电筒闪烁。我正在使用 Handler 和 Runnable 来模拟闪烁,但问题是在用户接听或取消呼叫后我无法停止处理程序。我的源代码:
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;
}
}
}