1

我有一个手电筒活动。通常它工作正常,但当我去任何其他活动时,它停止工作!

所以我想在回到 Flashlight Activity 时刷新代码。

我认为刷新使用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;

            }

        }
    });

}
  }                                                              
4

1 回答 1

2

您需要覆盖 onPause 和 onResume。在 onPause 中,您需要释放 Camera。在 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){
    }

}
于 2013-01-20T06:15:34.880 回答