gpt4 book ai didi

android - 使用 onResume() 刷新 Activity

转载 作者:行者123 更新时间:2023-11-29 21:51:01 25 4
gpt4 key购买 nike

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

所以我想在返回手电筒 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;

}

}
});

}
}

最佳答案

您需要覆盖 onPause 和 onResume。在 onPause 中,需要释放 Camera。在onResume中,需要重新请求。如果您在不进行 Activity 时尝试握住它,相机会不喜欢它。

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){
}

}

关于android - 使用 onResume() 刷新 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14422190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com