感谢 Paul Lammertsma 的建议。我通过添加保存相机对象的服务解决了这个问题。
收货人代码:
public class Receiver extends BroadcastReceiver {
SharedPreferences prefs = null;
boolean enabled = false;
@Override
public void onReceive(Context context, Intent intent) {
prefs = PreferenceManager.getDefaultSharedPreferences(context);
AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int ringState = am.getRingerMode();
enabled = prefs.getBoolean("full", false);
if (!enabled || ringState != AudioManager.RINGER_MODE_NORMAL) {
return;
}
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (TelephonyManager.EXTRA_STATE_RINGING.equals(state) ||
TelephonyManager.EXTRA_STATE_IDLE.equals(state) ||
TelephonyManager.EXTRA_STATE_OFFHOOK.equals(state)) {
context.startService(new Intent(context, MyService.class).putExtra("state", state));
}
}
}
服务代码:
public class MyService extends Service {
Camera cam = null;
boolean offhook = false;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String state = intent.getStringExtra("state");
if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH) && !offhook) {
cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
}
}
if (TelephonyManager.EXTRA_STATE_IDLE.equals(state)) {
if (!offhook) {
if (cam != null) {
cam.release();
cam = null;
}
this.stopSelf();
} else {
offhook = false;
}
}
if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(state)) {
offhook = true;
if (cam != null) {
cam.stopPreview();
cam.release();
cam = null;
}
this.stopSelf();
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
if (cam != null) {
cam.release();
cam = null;
}
super.onDestroy();
}
}