我有一个手电筒活动。通常它工作正常,但当我去任何其他活动,它停止工作!
所以我想在回到手电筒活动时刷新代码。
我认为使用onResume()
进行更新会对我有所帮助,但如何做到这一点?
public class FlashLightActivity extends Activity {
//flag to detect flash is on or off
private boolean isLighOn = false;
private Camera camera;
private Button next1, next2;
@Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
next1 = (Button) findViewById(R.id.ebtn28_answer);
next1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), FullScreen.class);
startActivityForResult(myIntent, 0);
}
});
next2 = (Button) findViewById(R.id.buttonFlashlight);
Context context = this;
PackageManager pm = context.getPackageManager();
// if device support camera?
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Log.e("err", "Device has no camera!");
return;
}
camera = Camera.open();
final Parameters p = camera.getParameters();
next2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if (isLighOn) {
Log.i("info", "torch is turn off!");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLighOn = false;
} else {
Log.i("info", "torch is turn on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLighOn = true;
}
}
});
}
}
答案 0 :(得分:2)
您需要覆盖onPause和onResume。在onPause中,您需要释放相机。在onResume中,您需要重新请求它。如果您在不是活动活动时尝试握住它,相机不喜欢它。
public void onPause(){
super.onPause();
if(camera != null){
camera.release();
camera = null;
}
}
public void onResume(){
super.onResume();
//Need to release if we already have one, or we won't get the camera
if(camera != null){
camera.release();
camera = null;
}
try {
camera = Camera.open();
}
catch (Exception e){
}
}