Android FlashLight教程

In this tutorial, we’ll be implementing the FlashLight feature in our application.

在本教程中,我们将在应用程序中实现FlashLight功能。

Android手电筒 (Android FlashLight)

Every smartphone nowadays has the flashlight feature/torch available through the camera flash.

如今,每个智能手机都具有可通过相机闪光灯使用的手电筒功能/手电筒。

In the next part, we’ll be using the Camera2 API to toggle the flashlight. The Camera API was deprecated since Android API 25. Also, we’ll see how to create a blinking flashlight.

在下一部分中,我们将使用Camera2 API切换手电筒。 自Android API 25起,不推荐使用Camera API。此外,我们还将介绍如何创建闪烁的手电筒。

Let’s get started by creating a new Android Studio project.

让我们开始创建一个新的Android Studio项目。

Android Studio Flash Light项目结构 (Android Studio Flash Light Project Structure)

(Code)

The code for the activity_main.xml layout file is given below:

下面给出了activity_main.xml布局文件的代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnFlashLightToggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="FLASHLIGHT OFF"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnBlinkFlashLight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="BLINK FLASHLIGHT"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnFlashLightToggle" />


</android.support.constraint.ConstraintLayout>

Add the following to your AndroidManifest.xml file inside the manifest tag.

将以下内容添加到清单标记中的AndroidManifest.xml文件中。

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

The code for the MainActivity.java class is given below:

MainActivity.java类的代码如下:

package com.journaldev.androidflashlight;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button btnFlashLight, btnBlinkFlashLight;
    private static final int CAMERA_REQUEST = 123;
    boolean hasCameraFlash = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST);

        hasCameraFlash = getPackageManager().
                hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

        btnFlashLight = findViewById(R.id.btnFlashLightToggle);
        btnBlinkFlashLight = findViewById(R.id.btnBlinkFlashLight);

        btnFlashLight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (hasCameraFlash) {
                    if (btnFlashLight.getText().toString().contains("ON")) {
                        btnFlashLight.setText("FLASHLIGHT OFF");
                        btnBlinkFlashLight.setText("BLINK FLASHLIGHT OFF");
                        flashLightOff();
                    } else {
                        btnBlinkFlashLight.setText("BLINK FLASHLIGHT ON");
                        btnFlashLight.setText("FLASHLIGHT ON");
                        flashLightOn();
                    }
                } else {
                    Toast.makeText(MainActivity.this, "No flash available on your device",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

        btnBlinkFlashLight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(btnFlashLight.getText().toString().contains("ON"))
                {
                    blinkFlash();
                }
                else{
                    Toast.makeText(MainActivity.this, "Press the above button first.",
                            Toast.LENGTH_SHORT).show();
                }

            }
        });


    }

    private void flashLightOn() {
        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

        try {
            String cameraId = cameraManager.getCameraIdList()[0];
            cameraManager.setTorchMode(cameraId, true);
        } catch (CameraAccessException e) {
        }
    }

    private void flashLightOff() {
        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            String cameraId = cameraManager.getCameraIdList()[0];
            cameraManager.setTorchMode(cameraId, false);
        } catch (CameraAccessException e) {
        }
    }

    private void blinkFlash()
    {
        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        String myString = "0101010101";
        long blinkDelay = 50; //Delay in ms
        for (int i = 0; i < myString.length(); i++) {
            if (myString.charAt(i) == '0') {
                try {
                    String cameraId = cameraManager.getCameraIdList()[0];
                    cameraManager.setTorchMode(cameraId, true);
                } catch (CameraAccessException e) {
                }
            } else {
                try {
                    String cameraId = cameraManager.getCameraIdList()[0];
                    cameraManager.setTorchMode(cameraId, false);
                } catch (CameraAccessException e) {
                }
            }
            try {
                Thread.sleep(blinkDelay);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case CAMERA_REQUEST:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    hasCameraFlash = getPackageManager().
                            hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
                } else {
                    btnFlashLight.setEnabled(false);
                    btnBlinkFlashLight.setEnabled(false);
                    Toast.makeText(MainActivity.this, "Permission Denied for the Camera", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}

In the above code, we first ask for the camera permissions.

在上面的代码中,我们首先要求相机权限。

Once that’s done, we check if the Camera flash feature is present or not.

完成后,我们将检查相机闪光灯功能是否存在。

btnFlashLight is used as a flashlight toggle button.

btnFlashLight用作手电筒切换按钮。

We start the flashlight by getting the first element from the camera id list over the CameraManager.

我们通过从CameraManager的相机ID列表中获取第一个元素来启动手电筒。

Over that id, we can set the torch mode to true to enable the flashlight or to false to disable it.

在该ID上,我们可以将手电筒模式设置为true以启用手电筒,或将其设置为false禁用手电筒。

如何使手电筒闪烁? (How to make the flashlight blink?)

We use a string which consists of a binary number. We iterate through the string and toggle the flashlight on each iteration while making the thread sleep for a moment to bring that blinking effect.

我们使用由二进制数组成的字符串。 我们遍历字符串,并在每次迭代时切换手电筒,同时使线程Hibernate一会儿以带来闪烁效果。

In order to make it blink endlessly use an infinite loop which stops on a condition.

为了使其不断闪烁,请使用无限循环,该循环在某种情况下停止。

The output of the above application is the desired one. We’ve omitted the screenshot since it is something that’s on the hardware.

以上应用程序的输出是所需的。 我们省略了屏幕截图,因为它是硬件上的内容。

This brings an end to this tutorial on FlashLight. You can download the project from the link below:

这结束了有关FlashLight的本教程。 您可以从下面的链接下载项目:

翻译自: https://www.journaldev.com/21685/android-flashlight-tutorial

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值