使用Camera2 API的Android Flash Light应用程序教程






4.20/5 (4投票s)
使用Camera2 API的Android Flash Light应用程序教程
在本文中,我们将解释如何创建一个免费的 Android 手电筒应用程序。本教程是“边做边学”系列教程的一部分,我们将向您展示如何创建简单的 Android 应用程序。这将是 Android 开发初学者的实践经验。 按照本教程,您可以创建最好的 Android 手机手电筒应用程序,并通过 Google Play 分发它。
创建新项目
请按照以下步骤操作
- 打开 Android Studio 并通过转到 **文件 => 新建 => 新建项目** 来创建一个新项目。 输入应用程序名称为 `LedFlashLight` 和您的公司域名。(我们使用了我们的公司域名,即 `androidtutorialpoint.com`。同样,您可以使用您自己的。)
- 单击下一步并选择最低 SDK。 我们保留了默认设置并单击下一步。
- 选择空活动并单击下一步。
- 在下一个屏幕中,输入活动名称为 `FlashLightActivity`,并记住勾选“生成布局”按钮,然后单击完成。
Gradle 将同步项目并解析所有依赖项。
添加使用相机和闪光灯的权限
打开您的 *AndroidManifest.xml* 文件并添加以下权限
<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.camera.flash" />
这些 `uses-permissions` 标签告诉 Android 操作系统我们的应用程序将需要访问 `CAMERA` 和 `FLASHLIGHT`。 同样,`uses-feature` 告诉您应用程序将使用什么功能。
Led 手电筒应用程序将仅在纵向模式下运行,因此在 `activity` 标签中添加以下内容。
android:screenOrientation="portrait"
完整的 *AndroidManifest.xml* 如下所示
AnroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidtutorialpoint.ledflashlight" >
<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.camera.flash" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".FlashLightActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
除了包名,其他所有内容都应该与您相同。
生成应用程序布局
打开 *activity_flash_light.xml* 并添加以下代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.camera2.MainActivity"
android:background="#000"
android:gravity="center">
<ImageButton
android:layout_gravity="center"
android:id="@+id/button_on_off"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000"
android:src="@drawable/off"/>
</LinearLayout>
我们正在使用一个 `ImageButton`。 当用户按下此按钮时,Led 手电筒将被切换。
添加功能
打开 *FlashLightActivity.java* 并声明以下变量。
FlashLightActivity.java
package com.androidtutorialpoint.ledflashlight;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
public class FlashLightActivity extends AppCompatActivity {
private CameraManager mCameraManager;
private String mCameraId;
private ImageButton mTorchOnOffButton;
private Boolean isTorchOn;
private MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("FlashLightActivity", "onCreate()");
setContentView(R.layout.activity_flash_light);
mTorchOnOffButton = (ImageButton) findViewById(R.id.button_on_off);
isTorchOn = false;
在这里,我们只是声明变量,在 `onCreate()` 方法中,我们为活动设置布局。我们还引用了来自布局的 `mTorchOnOffButton Button`。我们稍后会详细讨论这个。在这里,我们使用 `Camera2` API,因为 `Camera` API 现在已在 Android 中弃用。
我们需要检测设备是否具有**闪光灯**。如果设备不支持闪光灯,我们必须通过警报消息提醒用户。
在 `FlashActivity` 活动的上述代码下方添加以下代码。
FlashLightActivity
Boolean isFlashAvailable = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!isFlashAvailable) {
AlertDialog alert = new AlertDialog.Builder(FlashLightActivity.this)
.create();
alert.setTitle("Error !!");
alert.setMessage("Your device doesn't support flash light!");
alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
System.exit(0);
}
});
alert.show();
return;
}
如果您的手机不支持相机闪光灯,您将收到以下错误。
按下 **确定** 按钮后,应用程序将关闭。
接下来,我们向 `onCreate()` 方法添加代码以获取 `CameraManager` 对象。 然后,我们为我们的 Led 手电筒应用程序的开/关按钮设置 `OnClickListener()`。
在 `OnClickListener()` 中,我们检查手电筒当前是开启还是关闭,然后我们调用 `turnOffFlashLight()` 关闭闪光灯(如果手电筒已开启),并调用 `turnOnFlashLight()` 开启闪光灯(如果手电筒当前关闭)。
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
mCameraId = mCameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
mTorchOnOffButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if (isTorchOn) {
turnOffFlashLight();
isTorchOn = false;
} else {
turnOnFlashLight();
isTorchOn = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
接下来,我们添加 `turnOffFlashLight()` 和 `turnOnFlashLight()` 方法来分别关闭和打开闪光灯。 我们还将添加一个 `playOnOffSound` 方法来提供点击按钮的声音效果。
public void turnOnFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
playOnOffSound();
mTorchOnOffButton.setImageResource(R.drawable.on);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void turnOffFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, false);
playOnOffSound();
mTorchOnOffButton.setImageResource(R.drawable.off);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void playOnOffSound(){
mp = MediaPlayer.create(FlashLightActivity.this, R.raw.flash_sound);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
在 `turnOffFlashLight()` 中,我们通过设置关闭 Led 手电筒
`mCameraManager.setTorchMode(mCameraId, false);`。 同样,在 `turnOnFlashLight()` 中,我们通过设置 `mCameraManager.setTorchMode(mCameraId, true);` 以编程方式打开闪光灯。
在 `playOnOffSound()` 中,我们使用 `MediaPlayer` 类的 `create()` 方法来播放点击声音。
最后,通过添加以下代码来覆盖 Activity 生命周期方法。当用户最小化应用程序时,我们将关闭闪光灯,并且一旦用户返回到应用程序,如果闪光灯先前已开启,则将恢复。
@Override
protected void onStop() {
super.onStop();
if(isTorchOn){
turnOffFlashLight();
}
}
@Override
protected void onPause() {
super.onPause();
if(isTorchOn){
turnOffFlashLight();
}
}
@Override
protected void onResume() {
super.onResume();
if(isTorchOn){
turnOnFlashLight();
}
}
}
现在,在实际设备上运行该应用程序,打开手电筒,然后使用您自己的最亮的手电筒应用程序在黑暗中找到您的东西。 您可以通过单击顶部的**立即下载**按钮来下载 Android 手电筒应用程序的源代码。 您还可以通过单击上方的**下载 APK** 来下载手电筒 APK。