我有一个手电筒课,当我使用ledon()
手电筒时会打开。当我使用ledoff()
它时,它会关闭。但是,如果我再次尝试将其重新打开,我会用力关闭。如果我尝试,它会再次打开。
强制关闭的原因是什么?
import android.hardware.Camera;
import android.util.Log;
import static android.hardware.Camera.*;
/**
* Created by tyler on 8/13/13.
*/
public class Torch {
private static final String TAG = "Light";
private static Camera mCamera;
private static Camera.Parameters mParameters;
public static Camera getCameraInstance() {
Camera c = null;
try {
c = open();
} catch (Exception e) {
}
return c;
}
public static void ledon()
{
mCamera = getCameraInstance();
mParameters = mCamera.getParameters();
mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(mParameters);
Log.d(TAG, "Turn On");
}
public static void ledoff(MainActivity activity) {
String flashMode = mParameters.getFlashMode();
if (Camera.Parameters.FLASH_MODE_OFF.equals(flashMode)) {
mCamera = getCameraInstance();
}
mParameters = mCamera.getParameters();
mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
mCamera.setParameters(mParameters);
Log.d(TAG, "Turn Off");
}
}
编辑:这是我更新的代码,它会关闭并打开所有我想要的,但是当我打开它然后再次打开时,它会强制关闭。Logcat 下面的代码。
import android.hardware.Camera;
import android.util.Log;
/**
* Created by tyler on 8/13/13.
*/
public class Torch {
private static final String TAG = "Light";
private static Camera mCamera;
private static Camera.Parameters mParameters;
public static Camera getCameraInstance() {
Camera c = null;
try {
c = mCamera.open();
} catch (Exception e) {
}
return c;
}
public static void ledon() {
mCamera = getCameraInstance();
mParameters = mCamera.getParameters();
String flashMode = mParameters.getFlashMode();
if (! flashMode.equals(Camera.Parameters.FLASH_MODE_TORCH)) {
mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(mParameters);
Log.d(TAG, "Turn On");
}
}
public static void ledoff() {
String flashMode = mParameters.getFlashMode();
if (! flashMode.equals(Camera.Parameters.FLASH_MODE_OFF)) {
mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
mCamera.setParameters(mParameters);
mCamera.release();
Log.d(TAG, "Turn Off");
}
}
}
日志猫:
08-15 12:01:10.502 25951-25951/com.tyler.myapp W/dalvikvm: threadid=1: 线程退出未捕获异常 (group=0x4170f898) 08-15 12:01:10.522 25951-25951/com.tyler .myapp E/AndroidRuntime:致命异常:com.tyler.myapp.Torch.ledon(Torch.java:28)的主要 java.lang.NullPointerException