CameraFlash手电筒

时间:2021-08-03 07:19:05
有时候晚上找不到电棒,电灯,咱们可以写个小程序,利用照相机的闪光灯临时顶替
上代码: 1 package com.linux.cameraflash; import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast; public class MainActivity extends Activity {
private boolean isOpen=false;
private Camera camera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView img=(TextView)findViewById(R.id.img);
img.setOnClickListener(new View.OnClickListener() {
//TextView上放一张图片,点击图片打开闪光灯
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(!isOpen){
Toast.makeText(getApplicationContext(),
"您已打开了手电筒", Toast.LENGTH_LONG).show();
camera=Camera.open();
Parameters params=camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();//start flash!
isOpen=true;
}else{
Toast.makeText(getApplicationContext(),
"已关闭", Toast.LENGTH_SHORT).show();
camera.stopPreview();//关掉闪光灯
camera.release();//关掉照相机
isOpen=false;
}
}
});
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
return true;
} }

再在manifest中加入权限:

<uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.FLASHLIGHT"/>
    <uses-feature
        android:name="android.hardware.camera"/>
    <uses-feature
        android:name="android.hardware.autofocus"/>
    <uses-feature
        android:name="android.hardware.flash"/>

上述代码在我的4.2系统上运行良好,不知在其他厂商手机上怎么样