我们以360手机助手中有一款叫“最美手电筒”,效果图:
通过图中手电筒的开关来开启或关闭闪光灯,OK,以下是实现此功能的代码:
public class MainActivity extends Activity implements OnClickListener { private ImageView iv_off_on; private ImageView iv_light; private Parameters parameter = null; private Camera camera = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); initView(); initListener(); } private void initListener() { iv_off_on.setOnClickListener(this); } private void initView() { iv_off_on = (ImageView) findViewById(R.id.iv_off_on); iv_light = (ImageView) findViewById(R.id.iv_light); iv_light.setVisibility(View.INVISIBLE); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_off_on: if (iv_off_on.isSelected()) {// 关闭 iv_off_on.setSelected(false); iv_light.setVisibility(View.INVISIBLE); parameter.setFlashMode(Parameters.FLASH_MODE_OFF); camera.setParameters(parameter); camera.release(); } else {// 开启 iv_off_on.setSelected(true); iv_light.setVisibility(View.VISIBLE); camera = Camera.open(); camera.startPreview(); parameter = camera.getParameters(); parameter.setFlashMode(Parameters.FLASH_MODE_TORCH); camera.setParameters(parameter); } break; default: break; } } }
最后在AndroidManifest.xml中添加相应的权限:
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.autofocus" />
转载请注明出处:http://blog.csdn.net/hai_qing_xu_kong/article/details/45504303情绪控_
时间: 2024-10-29 08:39:42