当设备接到来电时,我试图让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循环中。我该怎么做?
答案 0 :(得分:0)
不要在onStartCommand中编写代码,因为此方法将在主线程上执行,因此很可能会得到ANR。 要停止LED闪烁,请在应答或拒绝呼叫时中断线程,并使循环中断退出循环。