我正在尝试使LED闪光灯在设备收到来电时闪烁。这就是我在服务类中的做法。
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) {
String myString = "01010101010101010101";
long blinkDelay = 50;
for (int i = 0; i < myString.length(); i++) {
if (myString.charAt(i) == '0') {
// params.setFlashMode(Camera.Parameters.FLASH_MODE_ON);
cam = Camera.open();
Camera.Parameters p = cam.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
} else {
// params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
offhook = true;
if (cam != null) {
cam.stopPreview();
cam.release();
cam = null;
}
this.stopSelf();
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
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();
}
}
但是即使在我参加或拒绝呼叫后,眨眼也不会停止,因为它处于 for 循环中。我该怎么做?
不要在 onStartCommand 中编写代码,因为此方法将在主线程上执行,因此您可能会获得 ANR。要停止 LED 闪烁,请在接听或拒绝呼叫时中断线程,并放置一个 for 循环中断以退出循环。