package com.loaderman.flashlightdemo; import android.hardware.Camera; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button statusButton = null; private Camera camera = null; private Camera.Parameters parameters = null; public static boolean statusFlag = true; private int back = 0;// 判断按几次back @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); statusButton = (Button) findViewById(R.id.statusButton); statusButton.setOnClickListener(new Mybutton()); } class Mybutton implements View.OnClickListener { @Override public void onClick(View v) { if (statusFlag) { statusButton.setText("关闭闪光灯"); camera = Camera.open(); parameters = camera.getParameters(); parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);// 开启 camera.setParameters(parameters); statusFlag = false; } else { statusButton.setText("开启闪光灯"); parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);// 关闭 camera.setParameters(parameters); statusFlag = true; camera.release(); } } } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { back++; CloseApp(); } return false;// 设置成false让back失效 ,true表示 不失效 } public void CloseApp() { // 关闭程序 if (statusFlag) {// 开关关闭时 this.finish(); android.os.Process.killProcess(android.os.Process.myPid());// 关闭进程 } else if (!statusFlag) {// 开关打开时 camera.release(); this.finish(); android.os.Process.killProcess(android.os.Process.myPid());// 关闭进程 statusFlag = true;// 避免,打开开关后退出程序,再次进入不打开开关直接退出时,程序错误 } } }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.loaderman.flashlightdemo.MainActivity"> <Button android:id="@+id/statusButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="闪光灯" /> </RelativeLayout>
添加权限:
<uses-permission android:name="android.permission.CAMERA"/> <uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.autofocus"/>
效果需在真机测试即可