新手學習android作得一個閃光燈手電筒(測試過不少機型均可以)

看到不少剛學習的同志都很糾結按照網上不少代碼的實現方法都打開不了閃光燈,確實剛開始也有同感滴啦!但願能給大家一些思路!java

廢話很少說先上幾張圖片(有圖有真像哦!!!!!!!)android

 

思路:開啓閃光燈的方法app

我是這樣作的ide

 package com.cai.helloworld;
import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CameraPreview extends SurfaceView implements
  SurfaceHolder.Callback {
 private Camera mCamera;
 private SurfaceHolder mHolder;
 public static final String TAG = "CameraPreview";
 public CameraPreview(Context context) {
  super(context);
 }
 @SuppressWarnings("deprecation")
 public CameraPreview(Context context, Camera camera) {
  super(context);
  mCamera = camera;
  mHolder = getHolder();
  mHolder.addCallback(this);
  // deprecated setting, but required on Android versions prior to 3.0
  mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
 }
 @Override
 public void surfaceCreated(SurfaceHolder holder) {
  // The Surface has been created, now tell the camera where to draw the
  // preview.
  try {
   mCamera.setPreviewDisplay(holder);
   mCamera.startPreview();
  } catch (IOException e) {
   Log.d(TAG, "Error setting camera preview: " + e.getMessage());
  }
 }
 @Override
 public void surfaceChanged(SurfaceHolder holder, int format, int width,
   int height) {
  // If your preview can change or rotate, take care of those events here.
  // Make sure to stop the preview before resizing or reformatting it.
  if (mHolder.getSurface() == null) {
   // preview surface does not exist
   return;
  }
  // stop preview before making changes
  try {
   mCamera.stopPreview();
  } catch (Exception e) {
   // ignore: tried to stop a non-existent preview
  }
  // set preview size and make any resize, rotate or
  // reformatting changes here
  // start preview with new settings
  try {
   mCamera.setPreviewDisplay(mHolder);
   mCamera.startPreview();
  } catch (Exception e) {
   Log.d(TAG, "Error starting camera preview: " + e.getMessage());
  }
 }
 @Override
 public void surfaceDestroyed(SurfaceHolder holder) {
  // TODO Auto-generated method stub
 }
}

獲取CameraPreview後就能夠對閃光燈進行操做佈局

下面就是手電筒Demo的例子:學習

 package com.cai.helloworld;
import java.util.List;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.provider.Settings;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends Activity {
 protected static final String TAG = ">>>>>>>MainActivity";
 private Camera mCamera;
 private CameraPreview mPreview;
 private FrameLayout preview;
 private boolean isopent;
 private boolean isCameraExist;
 private ImageButton captureButton;
 private int defualtLigth;
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  setContentView(R.layout.activity_main);
  defualtLigth = getScreenBrightness(this);
  isCameraExist = checkCameraHardware(this);
  if (isCameraExist) {
   controlFlashLigth();
  } else {
   Toast.makeText(this, "您的設備沒有照相功能或者此功能不可用", Toast.LENGTH_LONG)
     .show();
  }
 }
 public void controlFlashLigth() {
  // Create an instance of Camera
  captureButton = (ImageButton) findViewById(R.id.button_capture);
  mCamera = getCameraInstance();
  // Create our Preview view and set it as the content of our
  // activity.
  mPreview = new CameraPreview(this, mCamera);
  preview = (FrameLayout) findViewById(R.id.camera_preview);
  preview.addView(mPreview);
  preview.setVisibility(View.INVISIBLE);
  captureButton.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    if (!isopent) {
     v.setBackgroundResource(R.drawable.flashlight_on);
     Toast.makeText(getApplicationContext(), "手電筒已開啓",
       Toast.LENGTH_SHORT)
     .show();
     turnLightOn(mCamera);
     isopent = true;
    } else {
     v.setBackgroundResource(R.drawable.flashlight_off);
     Toast.makeText(getApplicationContext(), "手電筒已關閉",
     Toast.LENGTH_SHORT).show();
     turnLightOFF(mCamera);
     isopent = false;
    }
   }
  });
 }
 /** A safe way to get an instance of the Camera object. */
 public static Camera getCameraInstance() {
  Camera c = null;
  try {
   c = Camera.open(); // attempt to get a Camera instance
  } catch (Exception e) {
   // Camera is not available (in use or does not exist)
  }
  return c; // returns null if camera is unavailable
 }
 /** Check if this device has a camera */
 public boolean checkCameraHardware(Context context) {
  if (context.getPackageManager().hasSystemFeature(
    PackageManager.FEATURE_CAMERA)) {
   // this device has a camera
   return true;
  } else {
   // no camera on this device
   return false;
  }
 }
 @Override
 protected void onResume() {
  super.onResume();
  Log.e(TAG, "onResume>>>>>runtime");
 }
 @Override
 protected void onPause() {
  super.onPause();
  Log.e(TAG, "onPause>>>>>runtime");
 }
 @Override
 protected void onDestroy() {
  super.onDestroy();
  Log.e(TAG, "onDestroy>>>>>runtime");
  releaseCamera();
 }
 @Override
 protected void onStop() {
  super.onStop();
  Log.e(TAG, "HomeANXIALE>>>onStop>>>>>runtime");
 }
 private void releaseCamera() {
  if (mCamera != null) {
   mCamera.release(); // release the camera for other applications
   mCamera = null;
  }
 }
 public void turnLightOn(Camera mCamera) {
  if (mCamera == null) {
   return;
  }
  Parameters parameters = mCamera.getParameters();
  if (parameters == null) {
   return;
  }
  List<String> flashModes = parameters.getSupportedFlashModes();
  // Check if camera flash exists
  if (flashModes == null) {
   // Use the screen as a flashlight (next best thing)
   captureButton.setBackgroundColor(this.getResources().getColor(
     R.color.white));
   setBrightness(this, 255);
   return;
  }
  String flashMode = parameters.getFlashMode();
  if (!Parameters.FLASH_MODE_TORCH.equals(flashMode)) {
   // Turn on the flash
   if (flashModes.contains(Parameters.FLASH_MODE_TORCH)) {
    parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
    mCamera.setParameters(parameters);
   } else {
   }
  }
 }
 public void turnLightOFF(Camera mCamera) {
  if (mCamera == null) {
   return;
  }
  Parameters parameters = mCamera.getParameters();
  if (parameters == null) {
   return;
  }
  List<String> flashModes = parameters.getSupportedFlashModes();
  // Check if camera flash exists
  if (flashModes == null) {
   setBrightness(this, defualtLigth);
   // Use the screen as a flashlight (next best thing)
   return;
  }
  String flashMode = parameters.getFlashMode();
  if (!flashMode.equals(Parameters.FLASH_MODE_OFF)) {
   // Turn on the flash
   if (flashModes.contains(Parameters.FLASH_MODE_OFF)) {
    parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
    mCamera.setParameters(parameters);
   } else {
   }
  }
 }
 /**
  * 獲取屏幕的亮度
  * 
  * @param activity
  * @return
  */
 public static int getScreenBrightness(Activity activity) {
  int nowBrightnessValue = 0;
  ContentResolver resolver = activity.getContentResolver();
  try {
   nowBrightnessValue = android.provider.Settings.System.getInt(
     resolver, Settings.System.SCREEN_BRIGHTNESS);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return nowBrightnessValue;
 }
 /**
  * 設置屏幕的亮度
  * 
  * @param activity
  * @return
  */
 public static void setBrightness(Activity activity, int brightness) {
  // Settings.System.putInt(activity.getContentResolver(),
  // Settings.System.SCREEN_BRIGHTNESS_MODE,
  // Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
  WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
  lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);
  // lp.screenBrightness =(brightness) * (1f / 255f);
  activity.getWindow().setAttributes(lp);
    }
}

接下來就是新建一個佈局文件activity_main.xmlui

佈局中用到Framelayout,首先camera_preview用於獲取camerapreview,以後用ImageButton對其進行覆蓋。this

 <FrameLayout xmlns:android=""
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <FrameLayout
        android:id="@+id/camera_preview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
    <ImageButton
        android:id="@+id/button_capture"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/flashlight_off"
        android:layout_gravity="center" />
</FrameLayout>

第一次寫這個也不知道要說些什麼,有什麼看不懂的能夠留言提問,會及時回答的spa

相關文章
相關標籤/搜索